Sometimes the usual test log and screenshot is not enough to find the reason of the failed test case. Especially when the test case occasionally fails in special circumstances and it is really hard to reproduce. For this reason, we need to collect for each fail as much information as possible. One possible source of information is the console output of the browser.

First we need to set which type of logs we want to track with Selenium’s WebDriver. The possible log types are located in class LogType. Create an instance of LoggingPreferences and enable desired log types to keep tracking of them. Create a DesiredCapability object and set LOGGING_PREFS capability to use the already created LoggingPreferences. Once you applied the DesiredCapability on the instance of WebDriver, you are ready to go.

Short code example:

		LoggingPreferences logs = new LoggingPreferences();
		logs.enable(LogType.BROWSER, Level.ALL);
		// logs.enable(LogType.CLIENT, Level.ALL);
		logs.enable(LogType.DRIVER, Level.ALL);
		logs.enable(LogType.PERFORMANCE, Level.ALL);
		// logs.enable(LogType.PROFILER, Level.ALL);
		// logs.enable(LogType.SERVER, Level.ALL);		
		dc.setCapability(CapabilityType.LOGGING_PREFS, logs);
		driver = new ChromeDriver(dc);

During the test case execution you can access any time to the console log by calling:

Logs logs = getDriver().manage().logs();

To print the captured logs you need to iterate through all of them and use any kind of Logger or simply use System.out.println(). You can also write it to an external file. Here is a little example, how you can print out the captured logs using slf4j Logger.

	LogEntries logEntries = logs.get(logType);
	if (!logEntries.getAll().isEmpty()){
		logger.debug("Console output from browser:" );
		for (LogEntry logEntry : logEntries) {
		   logger.debug("JS: " + logEntry.getLevel() + ": " + logEntry.getMessage());

    3 Responses to “Read out browser console logs in java with selenium 2.53.1”

  1. Muthu vignesh says:

    Really helpful content. What can be done if i need to get the contents like for example, if the response contains an array of data. How can i get those data. Is there any way. If so, please let me know

  2. Jochen Go says:

    Thanks for your example! Do you get the same output which you get when opening developer console directly in browser? In my case i am not receiving any lines which are written by my jsIP-Framework via console.log / console.error / …
    That is kinda annoying, my main target is to locate JS-Errors including stacktrace, so I need an error handler in framework which writes these lines after getting required informations instead of a direct browser JS-Error (which your example logs just fine).

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>