Setting Up Log4j Logging in Selenium Java Projects

When working on Selenium-based automation projects in Java, debugging test failures or understanding test behavior becomes much easier with a robust logging mechanism. While System.out.println() can serve basic needs, professional test frameworks require structured logging—and that’s where Log4j comes into play.

Apache Log4j is a powerful and flexible logging framework that allows developers to record log messages at different levels (INFO, DEBUG, ERROR, etc.), redirect output to multiple destinations (console, file, etc.), and format logs consistently. In this blog, we’ll walk through setting up Log4j 2 in a Selenium Java project.


Why Use Log4j in Selenium?

Better Debugging: Understand what went wrong and when.

Cleaner Code: Avoid cluttering your test scripts with print statements.

Persistent Logs: Save logs to a file for audit or post-run analysis.

Custom Log Levels: Easily filter logs (e.g., only errors, or detailed debug).


Step-by-Step Guide to Set Up Log4j 2

1. Create a Maven Project

Start by creating a Maven-based Selenium Java project in your preferred IDE (e.g., IntelliJ IDEA or Eclipse).


2. Add Dependencies to pom.xml

Add the Log4j 2 dependencies:

xml


<dependencies>

    <!-- Log4j Core -->

    <dependency>

        <groupId>org.apache.logging.log4j</groupId>

        <artifactId>log4j-core</artifactId>

        <version>2.20.0</version>

    </dependency>


    <!-- Log4j API -->

    <dependency>

        <groupId>org.apache.logging.log4j</groupId>

        <artifactId>log4j-api</artifactId>

        <version>2.20.0</version>

    </dependency>

</dependencies>


3. Add Log4j Configuration File

Create a file named log4j2.xml under the src/main/resources directory:

xml


<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="INFO">

    <Appenders>

        <Console name="Console" target="SYSTEM_OUT">

            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

        </Console>

        <File name="FileLogger" fileName="logs/selenium-log.log">

            <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>

        </File>

    </Appenders>

    

    <Loggers>

        <Root level="debug">

            <AppenderRef ref="Console"/>

            <AppenderRef ref="FileLogger"/>

        </Root>

    </Loggers>

</Configuration>

This config logs all messages at DEBUG level and above to both the console and a file.


4. Use Log4j in Selenium Test Classes

java


import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;


public class SampleTest {

    private static final Logger logger = LogManager.getLogger(SampleTest.class);


    public static void main(String[] args) {

        logger.info("Starting the Selenium test...");


        WebDriver driver = new ChromeDriver();

        logger.debug("Launched Chrome browser.");


        driver.get("https://example.com");

        logger.info("Navigated to example.com");


        String title = driver.getTitle();

        logger.info("Page title: " + title);


        driver.quit();

        logger.info("Test completed and browser closed.");

    }

}


Tips for Effective Logging

Use Different Levels: Use debug for internal info, info for checkpoints, and error for failures.

Avoid Sensitive Info: Don’t log passwords or confidential data.

Rotate Logs: Use rolling file appenders for long-running tests.


Conclusion

Setting up Log4j in your Selenium Java projects brings professionalism and clarity to your automation framework. It helps testers and developers quickly diagnose issues, trace test flows, and maintain logs for future analysis. With just a few lines of configuration, you can transform your Selenium framework into a much more reliable and maintainable solution. 

Learn Selenium with Java Training

Read More: Handling Multiple Windows in Selenium WebDriver Java
Read More: Using Assertions in Selenium Java with TestNG
Read More: Automating Login Functionality Using Selenium Java


Visit Our IHUB Talent Institute Hyderabad
Get Direction 

Comments

Popular posts from this blog

How to Use Tosca's Test Configuration Parameters

Installing Java and Eclipse IDE for Selenium Automation

How Flutter Works Behind the Scenes