I want to collect all the console error messages that appear in the console with Selenium WebDriver C #. I just want console errors like
CodePudding user response:
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;
}