Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium - How to log every step that is being performed?

I'm trying to find a way to log every action performed by the selenium driver object. Log4j is the commonly suggested solution. However, dedicated log statements are needed to add to the log as below -

driver.findElement(By.name("opt1")).sendKeys("km");
log.debug("selecting distance unit");
driver.findElement(By.name("opt2")).sendKeys("10");
log.debug("selecting distance value");

So i have to have log statements wherever i need to log. Is there anything which tracks the actions of the selenium driver and gives a general log?

like image 622
nivasan89 Avatar asked Oct 31 '22 00:10

nivasan89


1 Answers

Extend the WebDriver class you are using and override the log function, this function gets called before and after each function call.

Example:

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.SessionId;

public class MyWebDriver extends ChromeDriver {
    @Override
    protected void log(SessionId sessionId, String commandName, Object toLog, When when) {
        System.out.println("LOG: sessionId: " + sessionId + " when: " + when + " commandName: " + commandName + " toLog: " + toLog);
        super.log(sessionId, commandName, toLog, when);
    }
}

This code will give you output that look like this:

LOG: sessionId: 70521460-9ccf-4619-97ea-e7be4717a9b8 when: BEFORE commandName: findElement toLog: [70521460-9ccf-4619-97ea-e7be4717a9b8, findElement {using=xpath, value=//*[@hint='Username']}]
LOG: sessionId: 70521460-9ccf-4619-97ea-e7be4717a9b8 when: AFTER commandName: findElement toLog: [70521460-9ccf-4619-97ea-e7be4717a9b8, findElement {using=xpath, value=//*[@hint='Username']}]
LOG: sessionId: 70521460-9ccf-4619-97ea-e7be4717a9b8 when: BEFORE commandName: findElement toLog: [70521460-9ccf-4619-97ea-e7be4717a9b8, findElement {using=xpath, value=//*[@id='Password']}]
LOG: sessionId: 70521460-9ccf-4619-97ea-e7be4717a9b8 when: AFTER commandName: findElement toLog: [70521460-9ccf-4619-97ea-e7be4717a9b8, findElement {using=xpath, value=//*[@id='Password']}]
like image 80
Deddy Avatar answered Nov 04 '22 06:11

Deddy