0

I am logging all the events in the Selenium project with C# and NUnit using ThreadStatic attribute because every test is created in a different thread. The problem I am facing is inside the CreateDriver method. The event is being opened in a new thread and now the internalLog variable in the LoggingClass is in a different thread. As a result, the variable is null. I am looking for a way to log the messages in the same ExtentTest as the other messages of the test.

Technology:

  • C#
  • Selenium
  • NUnit
  • ExtentReports
public class LoggingClass
{
    [ThreadStatic]
    private static ExtentTest internalLog;

    private void LogMessage(Status status, string message)
    {
        internalLog.Log(status, message);
    }
}

public class GlobalEnvironment
{
    // I initialize the log here
    public static ILog Logger => applicationLogger;
}

public class Driver
{
    public static IWebDriver CreateDriver()
    {       
        // I create the driver here and then I subscribe to the event for the console

        IJavaScriptEngine monitor = new JavaScriptEngine(driver);
        List<string> consoleMessages = new List<string>();
        monitor.JavaScriptConsoleApiCalled += (sender, e) =>
        {
            GlobalEnvironment.Logger.Info($"Log: {e.MessageContent}");
        };
        await monitor.StartEventMonitoring();
    }
}

1 Answers1

0

I modified the ExtentTest variable. Instead of working with threads, now I have a dictionary with the full name of the tests where I save the logs based on the test name. It looks like this:

public class LoggingClass
{
    private ConcurrentDictionary<string, ExtentTest> internalLogs;

    private void LogMessage(Status status, string message)
    {
        ExtentTest result;
        if (internalLogs.TryGetValue(TestContext.CurrentContext.Test.FullName, out result)) 
        {
            result.Log(status, message);
        }        
    }
}