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.
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.
log4j
log4j
consists of the three main components.
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 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
.
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.
%t
specifies the thread name.
%-5level
is the level of the logging event.
%logger
is the name of the logger
which generated the logging event.
%msg
replaces 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.
log4j.xml
fileShown 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>
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
status
refers 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
status
toINFO
, log4j will log levels includingINFO
, and above (WARN
,ERROR
, andFATAL
messages)
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); } } }
Line 1: It specifies the name of the package
to which the files belong.
Lines 3–14: These lines make all the necessary imports including the logging
classes from Apache Log4j.
Lines 17–18: It declares a class
named Main
. A logger
object is created which is essential to log statements to the console or a file as you specify in the log4j.xml
file.
Line 20: public
specifies that the main
method can be accessed from anywhere in the program. static
allows the main
method to be called without creating any instance. void
indicates that the main
does not return any value. main
method takes the parameter string args[]
, a list of string arguments. Doing this allows you to pass values from the command line to your java
programs.
Line 22: It uses the WebDriverManager
to download and set up the chromedriver
.
Lines 24–31: These lines create an instance of ChromeOptions
, configure it with various arguments, and then create a ChromeDriver
instance with the options specified. It sets up the Chrome browser for automated testing.
Line 33: It creates an object named wait
with a timeout of 50
seconds. 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.info
in the try
block is used to print the message that the navigation to Google is successful. In the catch
block, the error
gets printed using logger if the navigation fails.
Lines 46–57: These lines find the search bar on the Google homepage by using the name
attribute. It then submit
the query and logs the message indicating that the search is successful.
Lines 59–78: The try
block waits for the first search result to become visible. It retrieves the URL of the first search, click
on the link, and wait
for the page to load. In the catch
block, an error
message is logged if the operations in the try
block are not successful.
Lines 81–84: The error
message is logged if the operations specified in the try
block are not successful.
Note:
Check the terminal tab for the log messages.
Check the output tab for the automation.
Free Resources