In the previous tutorial, we got an introduction to Log4j 2. In this tutorial, we will create a Selenium project and implement logging using the Log4j2 YML configuration.
Table of Contents
Prerequisite
- Java installed
- Maven installed
- TestNG installed
Dependency List
- Java -17
- Selenium – 4.15.0
- TestNG – 7.8.0
- Maven – 3.8.1
- Log4j – 3.0.0-alpha1
To use Log4j with YAML configuration, we need to add log4j-core and jackson-databind-yml dependencies to the project.
<!-- Log4j Dependency -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>3.0.0-alpha1</version>
</dependency>
<!-- Jackson Dataformat YAML -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.16.0</version>
</dependency>
Implementation Steps
Step 1 – Create a new Maven Project
You can use any IDE or text editor that supports Java.
![](https://qaautomation.expert/wp-content/uploads/2023/09/image-115.png?w=361)
Step 2- Add the dependencies to the POM.xml
Add the log4j library to your project.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>Log4j2_Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Log4j2_Demo</name>
<url>http://maven.apache.org</url>
<properties>
<selenium.version>4.15.0</selenium.version>
<testng.version>7.8.0</testng.version>
<log4j.version>3.0.0-alpha1</log4j.version>
<jackson.version>2.16.0</jackson.version>
<maven.compiler.version>3.11.0</maven.compiler.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.surefire.failsafe.version>3.1.2</maven.surefire.failsafe.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- TestNG Dependency -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<!-- Log4j Dependency -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- Selenium Dependency -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<!-- Jackson Dataformat YAML -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven.surefire.failsafe.version}</version>
<configuration>
<skipTests>false</skipTests>
<skip>false</skip>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 3- Create the log4j2.yml configuration file
Create a resource folder in src/java named as resources.
![](https://qaautomation.expert/wp-content/uploads/2023/09/image-116.png?w=335)
Now, create a file – log4j2.yml under the src/test/resources directory.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image.png?w=352)
The log4j configuration file specifies how log4j should log information. Here is an example of a simple log4j configuration file:
Configuration:
status: warn
appenders:
Console:
name: LogToConsole
PatternLayout:
Pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
File:
name: File
fileName: logs/app.log
PatternLayout:
Pattern: "%d %p %C{1.} [%t] %m%n"
Loggers:
logger:
- name: com.example
level: debug
additivity: false
AppenderRef:
- ref: LogToConsole
- ref: File
Root:
level: error
AppenderRef:
ref: LogToConsole
- We’ve defined the level of the root logger as DEBUG. This means that we’ll get all the log events with level DEBUG and above. We’ve also defined a name for the appender as LogToConsole and File.
- We want to direct the logs to the console as well as File, we assigned the Appender type as Console and File.
- We specify the pattern in which we want to print the log messages.
Step 4 – Import log4j in the Selenium script
We need to import the log4j library in the Selenium script, so that we can use it in your code. Here is an example of how to import log4j in the Selenium script:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Step 5 – Create a Logger instance
We need to create a Logger instance in the Selenium script so that we can use it to log information. Here is an example of how to create a Logger instance:
private static Logger logger = LogManager.getLogger();
Step 6 – Create the Test Code with Log4j
Here is a complete code example that demonstrates how to use log4j in Selenium:
package com.example;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
public class Log4j_XML_Example {
WebDriver driver;
By userName = By.name("username");
By passWord = By.name("password");
By loginBtn = By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/form/div[3]/button");
By loginTitle = By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/h5");
By dashboardPage = By.xpath("//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h6");
By actualErrorMessage = By.xpath("//*[@class='orangehrm-login-error']/div[1]/div[1]/p");
// Creating a logger
private static Logger logger = LogManager.getLogger();
@BeforeMethod
public void setUp() {
logger.info("Open a Chrome Web Browser");
ChromeOptions options=new ChromeOptions();
logger.info("Make the Web Browser full screen");
options.addArguments("--start-maximized");
driver=new ChromeDriver(options);
logger.info("Wait for 10 sec");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://opensource-demo.orangehrmlive.com/");
logger.info("Open the application");
}
@Test(description = "This test validates title of login functionality", priority = 0)
public void verifyLoginPageTitle() {
logger.info("Verify the Login page title");
String expectedTitle = driver.findElement(loginTitle).getText();
logger.info("Expected Title :" + expectedTitle);
Assert.assertTrue(expectedTitle.equalsIgnoreCase("Login"));
}
@Test(description = "This test validates successful login to Home page", priority = 1)
public void verifyloginPage() {
logger.info("Enter Username");
driver.findElement(userName).sendKeys("Admin");
logger.info("Enter Password");
driver.findElement(passWord).sendKeys("admin123");
driver.findElement(loginBtn).submit();
logger.info("New page - Dashboard is opened");
String newPageText = driver.findElement(dashboardPage).getText();
logger.info("Heading of new page :" + newPageText);
Assert.assertTrue(newPageText.contains("Dashboard"));
}
@Test(description = "This test validates unsuccessful login", priority = 2)
public void verifyIncorrectCredentials() {
logger.info("Enter Username");
driver.findElement(userName).sendKeys("12345");
logger.info("Enter Password");
driver.findElement(passWord).sendKeys("admin123");
driver.findElement(loginBtn).submit();
logger.info("Error Message is displayed");
String ErrorMessage = driver.findElement(actualErrorMessage).getText();
logger.info("Error Message :" + ErrorMessage);
Assert.assertEquals(ErrorMessage, "Invalid credentials");
}
@AfterMethod
public void teardown() {
logger.info("Close the webpage");
driver.quit();
}
}
Step 7 – Execute the test
Right-click on the test and select “Run Log4j_XML_Example”.
![](https://qaautomation.expert/wp-content/uploads/2023/09/image-123.png?w=303)
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-1.png?w=1126)
Step 8 – View the logs
The log is printed as specified in the log4j2.yml file. The timestamp is specified in PatternLayout. The log type is INFO.
The output log file is created under folder logs that are created at the root level of the project. The file name is app.log.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-4.png?w=369)
The app.log file will look like the image shown below.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-3.png?w=784)
If you want to add RollingFile details in the file, you can refer to the below file for the same.
RollingFile:
- name: LogToRollingFile
fileName: logs/app.log
filePattern: "logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz"
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
Policies:
SizeBasedTriggeringPolicy:
size: 1KB
DefaultRollOverStrategy:
max: 5
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!