Get chrome's console log
Asked Answered
V

8

28

I want to build an automation testing, so I have to know the errors that appear in the console of chrome.

there is an option to get the error lines that appear in the console?

In order to see the console: right click somewhere in the page, click "inspect element" and then go to "console".

Vistula answered 15/8, 2013 at 20:35 Comment(2)
Does this help? #5057237Sibley
Why is the Java-based answer marked as the correct one, instead of the C# solutions?Yang
G
35

I don't know C# but here's Java code that does the job, I hope you can translate it to C#

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ChromeConsoleLogging {
    private WebDriver driver;


    @BeforeMethod
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");        
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);
        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
        driver = new ChromeDriver(caps);
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }

    public void analyzeLog() {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
            //do something useful with the data
        }
    }

    @Test
    public void testMethod() {
        driver.get("http://mypage.com");
        //do something on page
        analyzeLog();
    }
}

Pay attention to setUp method in above code. We use LoggingPreferences object to enable logging. There are a few types of logs, but if you want to track console errors then LogType.BROWSER is the one that you should use. Then we pass that object to DesiredCapabilities and further to ChromeDriver constructor and voila - we have an instance of ChromeDriver with logging enabled.

After performing some actions on page we call analyzeLog() method. Here we simply extract the log and iterate through its entries. Here you can put assertions or do any other reporting you want.

My inspiration was this code by Michael Klepikov that explains how to extract performance logs from ChromeDriver.

Gondi answered 17/8, 2013 at 0:15 Comment(4)
Whilst this is the correct answer for Java, as you point out, it's not C# and wouldn't work for C# once "translated" because the .NET API of Selenium doesn't support logs. As in, when you do Driver.Manage(), .Logs() will not be available. +1 anyway, since it shows the solution.Heddy
Is there still no way of getting Browser logs in C#?Magulac
I'm not sure why issue 6832 is still open, but for now .Logs works. We have WebDriver version 2.21, probablyPascha
So with your idea and code like this: var logs = driver.Manage().Logs.GetLog(LogType.Browser); I still cannot get the logs. May you please check this issue over here? Thanks in advance!Mandy
Y
24

You can get logs this way:

Driver().Manage().Logs.GetLog();

By specifying what log you are interested in you can get the browser log, that is:

Driver().Manage().Logs.GetLog(LogType.Browser);

Also remember to setup your driver accordingly:

ChromeOptions options = new ChromeOptions();
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
driver = new ChromeDriver("path to driver", options);
Yang answered 29/4, 2016 at 7:35 Comment(4)
Hi! It's not working for me, can you please check my issue? Thanks!Mandy
@BlackHat Sorry for the late reply! I updated my answer with the info from your thread.Yang
I did not have to set up logging mechanism when when starting the driver and Driver().Manage().Logs.GetLog(LogType.Browser); got me LogEntries containing errorUpsurge
Isn't that exactly what's intended here? @UpsurgeYang
H
4

This is the c# code for logging the brower log from chrome.

private void CheckLogs()
    {
        List<LogEntry> logs = Driver.Manage().Logs.GetLog(LogType.Browser).ToList();
        foreach (LogEntry log in logs)
        {
            Log(log.Message);
        }
    }

here is my code for the actual log:

        public void Log(string value, params object[] values)
    {
        // allow indenting
        if (!String.IsNullOrEmpty(value) && value.Length > 0 && value.Substring(0, 1) != "*")
        {
            value = "      " + value;
        }

        // write the log
        Console.WriteLine(String.Format(value, values));
    }
Hinze answered 28/11, 2016 at 16:27 Comment(0)
S
3

As per issue 6832 logging is not implemented yet for C# bindings. So there might not be an easy way to get this working as of now.

Spinal answered 16/11, 2015 at 11:39 Comment(1)
As far as I know - this should be the answer. There is not (to my knowledge) way to get the browser logs natively in Selenium with the C# language. Some of the comments mentioned it may be removed form other language bindings as well. I will be very happy to sew newer information about this but I think the latest one is - you're not going to have it.Catlin
L
1

Here is a solution to get Chrome logs using the C#, Specflow and Selenium 4.0.0-alpha05. Pay attention that the same code doesn't work with Selenium 3.141.0.

 [AfterScenario]
    public void AfterScenario(ScenarioContext context)
    {
        if (context.TestError != null)
        {         
            GetChromeLogs(context); //Chrome logs are taken only if test fails
        }
        Driver.Quit();
    }

    private void GetChromeLogs()
    {
        var chromeLogs = Driver.Manage().Logs.GetLog(LogType.Browser).ToList();            
    }
Lard answered 30/7, 2020 at 6:6 Comment(0)
S
0
public void Test_DetectMissingFilesToLoadWebpage()
    {
        try
        {
            List<LogEntry> logs = driver.Manage().Logs.GetLog(LogType.Browser).ToList();
            foreach (LogEntry log in logs)
            {
                while(logs.Count > 0)
                {
                    String logInfo = log.ToString();
                    if (log.Message.Contains("Failed to load resource: the server responded with a status of 404 (Not Found)"))
                    {
                        Assert.Fail();
                    }
                    else
                    {
                        Assert.Pass();
                    }
                }
            }
        }
        catch (NoSuchElementException e)
        {
            test.Fail(e.StackTrace);
        }
    }

You could do something like this in C#. It is a complete test case. Then print the console output as String i.e logInfo in your report. For some reason, Log(log.Message) from the solution above this one gave me build errors.So, I replaced it.

Subir answered 15/11, 2018 at 19:40 Comment(0)
M
0

C# bindings to the Chrome console logs are finally available in Selenium 4.0.0-alpha05. Selenium 3.141.0 and prior do not have support.

Before instantiating a new ChromeDriver object, set the logging preference in a ChromeOptions object and pass that into ChromeDriver:

ChromeOptions options = new ChromeOptions();   
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
ChromeDriver driver = new ChromeDriver(options);

Then, to write the Chrome console logs to a flat file:

    public void WriteConsoleErrors()
    {
        string strPath = "C:\\ConsoleErrors.txt";
        if (!File.Exists(strPath))
        {
            File.Create(strPath).Dispose();
        }

        using (StreamWriter sw = File.AppendText(strPath))
        {
            var entries = driver.Manage().Logs.GetLog(LogType.Browser);
            foreach (var entry in entries)
            {
                sw.WriteLine(entry.ToString());
            }
        }
    }
Monkhood answered 28/10, 2020 at 4:22 Comment(1)
ChromeOptions doesn't seem to have SetLoggingPreference() method in javaUpward
C
-1
driver.manage().logs().get("browser")

Gets all logs printed on the console. I was able to get all logs except Violations. Please have a look here Chrome Console logs not printing Violations

Civvies answered 5/2, 2018 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.