4

I want to collect all the console error messages that appear in the console with Selenium WebDriver + C #. I just want console errors like

Console errors Console errors

1 Answer 1

3

Follow these steps to collect browser logs and then output them.


1 - Create a function for collecting error logs
This function return a list of browser errors. like this:

    private List<string> GetBrowserError()
    {
        ILogs logs = this.Driver.Manage().Logs;
        var logEntries = logs.GetLog(LogType.Browser); // LogType: Browser, Server, Driver, Client and Profiler
        List<string> errorLogs = logEntries.Where(x => x.Level == LogLevel.Severe).Select(x => x.Message).ToList();
        return errorLogs;
     }

2 - Add the logs to TestContext
Like this:

    private void AddBorwserLogs()
    {
        string errors = "\n \n*** Errors ***\n \n";
        List<string> errorLogs = this.GetBrowserError();

        if (errorLogs.Count != 0)
        {
            foreach (var logEntry in errorLogs)
            {
                errors = errors + $"{logEntry}\n";
            }

        // Add errors to TestContext
        TestContext.WriteLine($"{errors}\nNumber of browser errors is: {errorLogs.Count}");
        }
     }

3 - Function calling
Call the AddBorwserLogs() function before test teardown. Like this:

    [TestCleanup]
    public void TeardownTest()
    {
        this.AddBorwserLogs();
        this.Driver.Close();
        this.Driver.Quit();
     }

Don't forget to initialize the WebDriver
Like this:

    public IWebDriver Driver;
    public TestContext TestContext { get; set; }

    [TestInitialize]
    public void SetupTest()
    {
        ChromeOptions options = new ChromeOptions();
        options.AddArguments("ignore-certificate-errors");
    
        this.Driver = new ChromeDriver(options);

        this.Driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 0, 70);
        var url = "https://www.selenium.dev/documentation/";
        this.Driver.Url = url;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work with Selenium 3.141.0, you need to upgrade or downgrade to avoid a null reference exception on this line: logs.GetLog(LogType.Browser)
This was a bug in .NET. It was fixed with Selenium 4. Therefore this solution only works with Selenium 4 and higher
I'm using selenium 4.8.2/ChromeDriver 111.x and needed to add options.SetLoggingPreference(LogType.Browser, LogLevel.All) to get this to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.