How to use log4j with selenium
Selenium is an open-source testing framework which supports browser automation. It provides a single interface allowing you to write applications in different programming languages such as python, Java, JavaScript, Ruby, Perl, C#, and PHP.
Log4j is a reliable logging framework written in Java. It is mainly used to log messages within the software.
How is log4j different from standard output
In Java, System.out.println() can print the output to the console or a file. The output on the console cannot be restored as soon as you close the terminal.
However, log4j allows you to specify logging levels which includes DEBUG, ERROR, FATAL, INFO, TRACE, and WARN. It provides multiple appenders which means that you can direct your output to multiple locations such as a console, file, and even remote servers, simultaneously.
Components of log4j
log4j consists of the three main components.
Loggers
Loggers are used in the code to log messages.
Logger logger = Logger.getLogger(MyClass.class);
Here,
Line 1: getLogger() creates a logger of the specified class. The method returns a suitable logger.
Appenders
Appenders are useful to write the logging information to the desired locations such as file, console, or even servers. Appenders are defined in the configuration file named log4j.xml.
Layouts
It determines the format of the log messages which can be specified in the configuration file.
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
Line 1:
%d{}specifies the date format.%tspecifies the thread name.%-5levelis the level of the logging event.%loggeris the name of theloggerwhich generated the logging event.%msgreplaces the message of the logging event.
The output would look like this.
08:25:45.689 [main] INFO packageName.className - A sample log message
Note:
The project assumes that you have selenium, java, and log4j already set up in your system.
The project is created using Maven.
Sample log4j.xml file
Shown below, is a sample log4j.xml file as specified on the Apache documentation.
<?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN"><Appenders><Console name="Console" target="SYSTEM_OUT"><PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/></Console></Appenders><Loggers><Root level="info"><AppenderRef ref="Console"/></Root></Loggers></Configuration>
Explanation
Line 1: It specifies the xml standard version and the encoding specifies the encoding method.
Line 2: The status is set to WARN which means that the events at WARN or more severe level will be displayed.
Note: The
statusrefers to the status of the internal log messages which the logging framework generates.
Logging levels organized from least to the most severe level are as follows:
TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF.
Note: If you set the
statustoINFO, log4j will log levels includingINFO, and above (WARN,ERROR, andFATALmessages)
Lines 4–8: This section defines the Appender in which you specify how the logging events should be written. We define a Console appender for the output to be written as standard output. The PatternLayout tag defines the format of the log messages.
Lines 10–14: It sets the level to INFO which means that events at INFO or a more severe level will be logged. The Root logger is set to Console appender specifying that all the generated log messages will be output to the console. You can choose to write the log messages to the file as well.
Main.java with loggers
A sample Main.java file along with the use of loggers is given below.
package amazon.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.NoSuchElementException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.JavascriptExecutor;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
options.addArguments("--disable-gpu");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--no-sandbox");
WebDriver driver = new ChromeDriver(options);
WebDriverWait wait = new WebDriverWait(driver, 50);
try {
logger.info("Start Test");
try
{
driver.get("https://www.google.com");
logger.info("Navigated to Google");
}
catch (Exception e)
{
logger.error("An error occurred ", e);
}
try
{
// Searching the tab
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("OnCollisionEnter not called whenever the two colliders collide educative");
searchBox.submit();
logger.info("Searched for the answer");
}
catch (Exception e)
{
logger.error("An error occurred ", e);
}
try
{
// Grab the first result
WebElement firstResult = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".g a")));
String resultLink = firstResult.getAttribute("href");
String resultText = firstResult.getText();
logger.info("First searched result: " + resultText + " Link: " + resultLink);
// Click the first result
firstResult.click();
logger.info("Opened the link");
// Waiting for the page to load
wait.until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
}
catch (NoSuchElementException e)
{
logger.error("An error occurred: ", e);
}
}
catch (Exception e)
{
logger.error("An error occurred", e);
}
}
}Explanation
Line 1: It specifies the name of the
packageto which the files belong.Lines 3–14: These lines make all the necessary imports including the
loggingclasses from Apache Log4j.Lines 17–18: It declares a
classnamedMain. Aloggerobject is created which is essential to log statements to the console or a file as you specify in thelog4j.xmlfile.Line 20:
publicspecifies that themainmethod can be accessed from anywhere in the program.staticallows themainmethod to be called without creating any instance.voidindicates that themaindoes not return any value.mainmethod takes the parameterstring args[], a list of string arguments. Doing this allows you to pass values from the command line to yourjavaprograms.Line 22: It uses the
WebDriverManagerto download and set up thechromedriver.Lines 24–31: These lines create an instance of
ChromeOptions, configure it with various arguments, and then create aChromeDriverinstance with the options specified. It sets up the Chrome browser for automated testing.Line 33: It creates an object named
waitwith a timeout of50seconds. It is used to wait for certain conditions to be fulfilled during automated test execution.Lines 35–44: These lines first navigate to the Google homepage.
driver.get()is wrapped inside a try catch block to handle exceptions occurred during test execution.Line 39 & 43:
logger.infoin thetryblock is used to print the message that the navigation to Google is successful. In thecatchblock, theerrorgets printed using logger if the navigation fails.Lines 46–57: These lines find the search bar on the Google homepage by using the
nameattribute. It thensubmitthe query and logs the message indicating that the search is successful.Lines 59–78: The
tryblock waits for the first search result to become visible. It retrieves the URL of the first search,clickon the link, andwaitfor the page to load. In thecatchblock, anerrormessage is logged if the operations in thetryblock are not successful.Lines 81–84: The
errormessage is logged if the operations specified in thetryblock are not successful.
Note:
Check the terminal tab for the log messages.
Check the output tab for the automation.
Continue reading about Selenium
Free Resources