Integrate Log4j 2 into Selenium - pragmatictesters/selenium-webdriver-examples GitHub Wiki

๐Ÿ”ง Integrate Log4j 2 into Selenium (Test Automation)

Logging is crucial for debugging and understanding the test execution flow. This guide walks you through integrating Log4j 2 into your Selenium project.


๐Ÿ“ฆ Step 1: Add Log4j 2 Dependencies to pom.xml

Add the following dependencies to your Maven project:

<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-core</artifactId>
   <version>2.24.3</version>
</dependency>

<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-api</artifactId>
   <version>2.24.3</version>
</dependency>

โœ… Replace the version with the latest one from Maven Central.


๐Ÿ›  Step 2: Create a Log4j 2 Configuration File

Create a file named log4j2.xml inside src/main/resources/.

Basic Configuration:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
   <Appenders>
       <Console name="Console" target="SYSTEM_OUT">
           <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
       </Console>
       <File name="File" fileName="logs/test.log">
           <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
       </File>
   </Appenders>
   <Loggers>
       <Root level="info">
           <AppenderRef ref="Console" />
           <AppenderRef ref="File" />
       </Root>
   </Loggers>
</Configuration>

Explanation:

  • Logs are shown in both console and logs/test.log file.
  • You can change the level to debug, info, warn, or error.
  • Customize the pattern to suit your formatting needs.

๐Ÿงช Step 3: Use Logger in Selenium Test Classes

Here's a practical example using Selenium WebDriver and TestNG:

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.testng.Assert;
import org.testng.annotations.*;

public class Log4JTest {

   private static final Logger logger = LogManager.getLogger(Log4JTest.class);
   WebDriver driver;

   @BeforeMethod
   public void setUp() {
       logger.info("Setting up WebDriver");
       driver = new ChromeDriver();
   }

   @Test
   public void testGoogleSearch() {
       logger.info("Navigating to Google");
       driver.get("https://www.google.com");

       logger.debug("Finding the search input box");
       boolean isDisplayed = driver.findElement(By.name("q")).isDisplayed();

       if (isDisplayed) {
           logger.info("Search input is visible");
       } else {
           logger.warn("Search input is NOT visible");
       }

       try {
           Assert.assertTrue(isDisplayed, "Search box should be visible");
       } catch (AssertionError e) {
           logger.error("Assertion failed: " + e.getMessage());
           throw e;
       }

       logger.info("Test completed");
   }

   @AfterMethod
   public void tearDown() {
       logger.info("Closing browser");
       driver.quit();
   }
}

๐Ÿ” Log Levels and When to Use Them

Log Level Purpose Selenium Example
DEBUG Detailed technical steps Element locators, waits
INFO Major events Test start/end, navigation
WARN Unexpected behavior Optional UI missing
ERROR Failures Assertion failure, exception
FATAL System crash Rare in tests, e.g., driver init fail

โœ… Verify the Logs

After running your tests:

  • Console Logs should show messages as per your configuration.
  • Log File: Go to the logs/ folder and open test.log.

๐Ÿงน Optional: Simplified Pattern for Console Output

Use this for cleaner, no-frills output:

<PatternLayout pattern="[%p] %m%n" />

โ™ป๏ธ Optional: Log File Rotation (Recommended for CI/CD)

<RollingFile name="RollingFile" fileName="logs/test.log"
             filePattern="logs/test-%d{yyyy-MM-dd-HH-mm}.log.gz">
   <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>
   <Policies>
       <TimeBasedTriggeringPolicy />
       <SizeBasedTriggeringPolicy size="10MB"/>
   </Policies>
</RollingFile>

๐Ÿ”„ Use in CI/CD Pipelines

In Jenkins or GitHub Actions:

  • Archive the logs/test.log file for review.
  • Adjust log levels dynamically based on test phase (e.g., use DEBUG during troubleshooting).

๐Ÿ’ก Why Use Log4j 2?

  • โœ… Easy to set up and extend
  • ๐Ÿ› ๏ธ Advanced features like async logging, rolling files
  • ๐Ÿ‘ Improves visibility into test failures and flow
  • ๐Ÿš€ Suitable for CI/CD and scalable projects
โš ๏ธ **GitHub.com Fallback** โš ๏ธ