In the previous tutorial, we got an introduction to Log4j 2. In this tutorial, we will see the process of splitting a log file daily basis.
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
Below is a very basic XML configuration for daily log split.
<RollingFile name="LogToRollingFile" fileName="logs/application.log"
filePattern="logs/%d{YYYY-MM}/application.%d{dd-MMM}-%i.log.gz">
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
</Policies>
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>
<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>
</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.xml 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)
Create the log4j2.xml configuration file in src/java/resources.
![](https://qaautomation.expert/wp-content/uploads/2023/09/image-118.png?w=334)
The log4j configuration file specifies how log4j should log information. Here is an example of a simple log4j configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="LogToConsole" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="LogToRollingFile" fileName="logs/application.log"
filePattern="logs/%d{YYYY-MM}/application.%d{dd-MMM}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.example" level="debug" additivity="false">
<AppenderRef ref="LogToRollingFile"/>
<AppenderRef ref="LogToConsole"/>
</Logger>
<Root level="error">
<AppenderRef ref="LogToRollingFile"/>
<AppenderRef ref="LogToConsole"/>
</Root>
</Loggers>
</Configuration>
If we want to roll over log files based on file size and date time, we need to use SizeBasedTriggeringPolicy and TimeBasedRollingPolicy.
In the given example, the appender able to refer to the file name pattern and time-based rollover strategy using the filePattern attribute, which includes {dd-MMM}. Time-based rollover will happen every day.
![](https://qaautomation.expert/wp-content/uploads/2023/11/image-181.png?w=410)
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:
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");
// 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"));
}
@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/11/image-162.png?w=1177)
Step 8 – View the logs
The output log file is created under folder logs that are created at the root level of the project. The file name is application.log.
application.log file created under folder – 2023-11. application.log is the current log. We can see that we have separate logs for each day.
![](https://qaautomation.expert/wp-content/uploads/2023/11/image-182.png?w=410)
The application.log file will look like the image shown below.
![](https://qaautomation.expert/wp-content/uploads/2023/11/image-168.png?w=743)
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!