Selenium C# Tutorial: Using Log Helpers

Updated: Jan 18

In computing, a log file is a file that records either events that occur in an operating system or other software runs or messages between different users of communication software. Logging is the act of keeping a log. In the simplest case, messages are written to a single log file. Wikipedia


So what will we cover in this tutorial? We will create a logging system in our automation framework to track records of what's happening behind the scene within the time of test execution.



There are two ways we can use to keep our logging to work:

  1. Outputting our records to an external data source/file is very handy if we need to audit our log in the future or if we require the file to be sent to other peers who do not have direct access to our system (usually customers that doesn't allow direct access to their systems).

  2. Outputting our records to a console mostly when we execute our tests via any CI tools, the CI tools usually have built-in tracking systems that can keep and track the history of every run by itself.

Let's start coding :)


Logger Class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Helpers
{
public class LogHelpers
{
//Declaration of the file stream and format 
private static string _logFile = string.Format("{0:yyyymmddhhmmss}", DateTime.Now);
public static StreamWriter stream = null;

//Create a file that will be used to store the log information
public static void CreateLogFile()
{
//create a directory
string filePath = @"F:\LogRecords\";

if (Directory.Exists(filePath))
{
stream = File.AppendText(filePath + _logFile + ".log");
}
else
{
Directory.CreateDirectory(filePath);
stream = File.AppendText(filePath + _logFile + ".log");
}
}

//Create a method that can write the information into the log file
public static void WriteToFile(string Message)
{
stream.Write("{0} {1}\t", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
stream.Write("\\T{0}", Message);
stream.Flush();
}
}
}

Test Example:

[TestMethod]
public void LogExample()
{
//Creating the Log File 
LogHelper.CreateLogFile();
            
LogHelper.WriteToFile("Test 1");
LogHelper.WriteToFile("Test 2");
LogHelper.WriteToFile("Test 3");
LogHelper.WriteToFile("Test 4");
}

[TestMethod]
public void LogExample_2()
{           
LogHelper.WriteToFile("Test 5");
LogHelper.WriteToFile("Test 6");
LogHelper.WriteToFile("Test 7");
LogHelper.WriteToFile("Test 8");
}

Output:




126 views0 comments