Selenium 4 – Chrome DevTools Log Entry Listeners


In Selenium 4, you can listen Chrome Console logs using "Devtools" interface. Let's see with an example.

Selenium 4.0 (Alpha) Maven Dependency
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-1</version>
</dependency>
Sample Code
DevTools devTools = ((ChromeDriver)driver).getDevTools();

devTools.createSession();
devTools.send(Log.enable());

devTools.addListener(Log.entryAdded(), entry -> System.out.println(entry.asSeleniumLogEntry()));

Using the above code, Chrome DevTools Console logs can be published in Log4j or LogBack files.

Full Code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.Log;
import org.slf4j.*;

public class Selenium4Devtools {
    final static Logger logger = LoggerFactory.getLogger(Selenium4Devtools.class);

    public static void main(String args[]){

        System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        try{

            DevTools devTools = ((ChromeDriver)driver).getDevTools();

            devTools.createSession();
            devTools.send(Log.enable());

            devTools.addListener(Log.entryAdded(), entry -> logger.error(entry.asSeleniumLogEntry().getMessage()));

            driver.get("https://www.codoid.com");

        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally {
            driver.quit();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *