Capturing browser logs with Selenium WebDriver using Java

We can capture the browser level logs or console logs using selenium. To capture browser logs we how to open the browser using DesiredCapabilities. Also we how to set the LoggingPreferences so that we can capture the level of logs.

If you want to see the locks present in the browser you might need to open the dev tools (CTRL+SHIFT+i) or right-click > inspect element..

For the example purpose, we will be using the below URL: https://chercher.tech/practice/explicit-wait
console-log-selenium

We have set the place from where we are going to retrieve the log, here in this example we will be retrieving the log from the browser.

DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

The complete program

import java.util.Date;
import java.util.logging.Level;

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;

public class BrowserLoggingChercherTech {
	
	public static void main(String[] args) throws Exception {
		String driverPath = "D:\\Eclipse progs\\driverserver\\chromedriver.exe";
		DesiredCapabilities caps = DesiredCapabilities.chrome();
		LoggingPreferences logPrefs = new LoggingPreferences();
		logPrefs.enable(LogType.BROWSER, Level.ALL);
		caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
	        
		System.setProperty("webdriver.chrome.driver", driverPath);
		WebDriver driver = new ChromeDriver();
		driver.get("https://chercher.tech/practice/explicit-wait");
		
		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
        }		  
	}
}

console-log-selenium-java-output

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions