How to Use Log4j in Selenium?

โšก Smart Summary

Log4j in Selenium is a fast, flexible Java logging framework that records flow details of automation scripts. It supports multiple log levels, appenders, and layouts, and pairs well with LogExpert for analyzing the generated log files.

  • ๐Ÿ”˜ Components: Log4j is built around Loggers, Appenders, and Layouts that together capture, route, and format log events for Selenium automation projects.
  • โ˜‘๏ธ Log Levels: Seven levels (ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF) control how much detail is recorded during script execution and debugging.
  • โœ… Appenders: ConsoleAppender, FileAppender, and RollingFileAppender decide whether log entries go to the console, a static file, or a rolling set of files.
  • ๐Ÿงช Configuration: A log4j.properties file defines root and application loggers, file paths, maximum file size, backup index, and PatternLayout formatting rules.
  • ๐Ÿ› ๏ธ LogExpert Viewer: The free LogExpert tool tails Selenium and Manual log files in real time, with filtering, bookmarking, highlighting, and multi-tab viewing.

How to Use Log4j in Selenium

What is Log4j in Selenium?

Log4j is a fast, flexible, and reliable logging framework (API) written in Java and developed in early 1996. It is distributed under the Apache Software License. Log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages. It is a tool used for small to large scale Selenium automation projects.

Why use Log4j?

Log4j offers several practical benefits for Selenium projects:

  • It is open source.
  • With Log4j, it is possible to store the flow details of Selenium automation in a file or database.
  • Log4j works for large as well as small projects.
  • In Log4j, log statements replace System.out.println statements in the code to know the status of a project while it is executing.

Log4j Components

Log4j Components

Loggers

The Logger is responsible for logging information. To implement loggers in a project, the following steps need to be performed.

Create an instance for the Logger class

The Logger class is a Java-based utility that has all the generic methods already implemented to use Log4j.

Define the Log4j level

Primarily there are seven kinds of log levels:

  1. ALL – This level of logging records everything (it turns all the logs on).
  2. DEBUG – prints debugging information and is helpful in the development stage.
  3. INFO – prints informational messages that highlight the progress of the application.
  4. WARN – prints information regarding faulty and unexpected system behavior.
  5. ERROR – prints error messages that might allow the system to continue.
  6. FATAL – prints system critical information that causes the application to crash.
  7. OFF – No logging.

Appenders

An Appender is used to deliver LogEvents to their destination. It decides what will happen with log information. In simple words, it writes logs to a file. The following are a few types of Appenders:

  1. ConsoleAppender logs to standard output.
  2. FileAppender prints logs to a specific file.
  3. RollingFileAppender writes to a file with a maximum size.

Note: In log4j.properties, an appender can be called with any name. There are other appenders as well, but the focus here is on these few.

Layouts

The Layout is responsible for formatting logging information in different styles.

The Logger class provides different methods to handle logging activities. It provides two static methods for obtaining a Logger object.

public static Logger getRootLogger()
public static Logger getLogger(String name)

How is Log4j configured?

To configure Log4j, decide which appender to implement. The parameters of the appender are set accordingly.

  • Use DEBUG level and RollingFileAppender.
  • Two configurations or logs are created:
    • First: a root logger, which writes all system-generated logs into a file named Selenium.logs.
    • Second: an application logger, which writes information generated by manual commands in code into the file named Manual.logs.
  • The layout used is PatternLayout.

#Root logger

log4j.rootLogger=DEBUG,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\Guru99\\src\\Selenium.logs
log4j.appender.file.maxFileSize=900KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.file.Append=false

#Application Logs

log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=900KB
log4j.appender.dest1.maxBackupIndex=6
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=D:\\Guru99\\src\\Manual.logs
log4j.appender.dest1.Append=false

In the above example, Log4j is configured to log into two different files named Selenium.log and Manual.log.

  • file and dest1 are the two identifiers.
  • “File” is used to give the file name in which logs are saved.
  • “maxFileSize” is used to configure the maximum size of the log file. When the file reaches this size, a new file is created with the same name, and the old file name receives an index suffix.
  • “maxBackupIndex” is used to configure the maximum number of files to back up.
  • “layout” is used to set the format of the log file.
  • “Append” is used to set the append function. When it is set to false, a new file is created every time rather than reusing the old file for logging.

How is Log4j used within a script?

In the code, “log” is used as a reference variable referencing the getLogger method of the Logger class.

Logger log = Logger.getLogger("devpinoyLogger");

Use the “log” reference variable and the debug method to log the information that is needed.

log.debug("--information--");

What is a LogExpert tool?

LogExpert is a tool with the following characteristics:

  1. LogExpert is a Windows tool developed to tail logs.
  2. It is a free and open source log viewer.
  3. It is a log analysis tool with multiple features such as searching, filtering, bookmarking, and highlighting logs.
  4. Log files get automatically updated when opened in this tool.
  5. Multiple log files can be opened in different tabs.
  6. Comments can be added to bookmarks, and a shortcut key navigates between different bookmarks. A complete bookmark list is available for navigation.
  7. Shortcuts of the tool are given in the help file so that they can be referred to as needed.

How to use Log4j in Selenium

Step 1) In Eclipse, create a new project with the name log4j_demo.

Use Log4j In Selenium

Step 2) Right click on src -> Build Path -> Configure Build Path.

Use Log4j In Selenium

Step 3) Click on Libraries and add the Log4j library. It can be downloaded from https://logging.apache.org/log4j/1.2/download.html.

Use Log4j In Selenium

Step 4) Create a new file. This file holds all the Log4j configuration.

  1. Right click on src -> New -> Other -> General -> File.
  2. Give the file name as “log4j.properties”.
  3. Click on Finish.

Create two more files and name them Selenium.logs and Manual.logs. These files contain all the logs created by the system and the manually logged statements.

Use Log4j In Selenium

Step 5) In log4j.properties, copy the entire configuration.

Use Log4j In Selenium

Step 6) Create the main class:

  1. Right click on the default package -> New -> Class.
  2. Give the class a name and click Finish.

Use Log4j In Selenium

Step 7) Copy the following code into the main class.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.apache.log4j.Logger;

public class LoggingDemo {
    /**
     * @param args
     */
    public static void main(String[] args) {
         // TODO Auto-generated method stub
         WebDriver driver = new FirefoxDriver();
         Logger log = Logger.getLogger("devpinoyLogger");

         driver.get("https://healthunify.com/bmicalculator/");
         log.debug("opening website");
         driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
         log.debug("entering weight");
         driver.findElement(By.name("wg")).sendKeys("87");
         log.debug("selecting kilograms");
         driver.findElement(By.name("opt1")).sendKeys("kilograms");
         log.debug("selecting height in feet");
         driver.findElement(By.name("opt2")).sendKeys("5");
         log.debug("selecting height in inches");
         driver.findElement(By.name("opt3")).sendKeys("10");
         log.debug("clicking on calculate");
         driver.findElement(By.name("cc")).click();

         log.debug("getting SIUnit value");
         String SIUnit = driver.findElement(By.name("si")).getAttribute("value");
         log.debug("getting USUnit value");
         String USUnit = driver.findElement(By.name("us")).getAttribute("value");
         log.debug("getting UKUnit value");
         String UKUnit = driver.findElement(By.name("uk")).getAttribute("value");
         log.debug("getting overall description");
         String note = driver.findElement(By.name("desc")).getAttribute("value");

         System.out.println("SIUnit = " + SIUnit);
         System.out.println("USUnit = " + USUnit);
         System.out.println("UKUnit = " + UKUnit);
         System.out.println("note = " + note);
        driver.quit();
    }
}

In the above code, the script visits https://healthunify.com/bmicalculator/ and verifies the BMI calculator. The weight entered is 87 KG and the height is 5 feet 10 inches. The script checks output in SI, US, and UK units.

Using Logger.getLogger(“devpinoyLogger”), the script creates system-level logs. Using the log.debug method, data is stored into Manual.log.

Step 8) Run the script. Open the location of Manual and Selenium logs to check the logging data.

How LogExpert tool can be used to analyze logs

  1. Download the tool from https://github.com/zarunbal/LogExpert. Go to the LogExpert download folder.

    LogExpert Tool Can Be Used To Analyze Logs

  2. Open LogExpert.exe.
  3. Click on File -> Open and browse to the path where Manual.log and Selenium.log files are stored. Select the file.
  4. Select the “Follow tail” option.

    LogExpert Tool Can Be Used To Analyze Log

    Selecting Follow tail enables tailing of logs, which means LogExpert automatically updates the log file while the script is in execution. With any other editor like Notepad, the file has to be closed and reopened repeatedly to update the logs. With LogExpert in Follow Tail mode, this is not required.

    The following images show the layout of the logs.

    LogExpert Tool Can Be Used To Analyze Log

    LogExpert Tool Can Be Used To Analyze Log

Using LogExpert, the logs created by the Selenium WebDriver can be debugged. In this tool, one can:

  • Search for any text and regular expression.
  • Create bookmarks and comment on them, and also navigate between bookmarks, which is not possible in any other tool.
  • Filter the logs, search for text ranges, and apply another filter to the previously filtered logs.
  • Highlight different lines based on certain words.

This tool also helps to partition the data into different columns.

FAQs

Log4j 1.x reached end of life in 2015 and uses a properties or XML file for configuration. Log4j 2.x offers better performance, asynchronous loggers, lambda support, and improved security after the Log4Shell patches, making it the recommended choice for new projects.

Log4j supports configurable log levels, persistent file output, rolling backups, and structured patterns. System.out.println writes only to the console and cannot be filtered or archived. Log4j makes Selenium test results easier to triage, audit, and reproduce.

Yes. AI assistants can parse large Log4j output, cluster repeated failures, and surface root-cause patterns across Selenium runs. They highlight flaky locators, slow steps, and stack traces, turning raw log lines into prioritized action items for QA engineers.

AI-driven observability platforms ingest Log4j streams, detect anomalies in real time, and predict failures before they impact users. Machine learning models score severity, deduplicate noisy events, and trigger smart alerts, replacing manual grep workflows with proactive monitoring.

No. LogExpert is a popular free Windows viewer with tail-follow and filtering, but alternatives include BareTail, glogg, Klogg, and full platforms like Splunk, Graylog, or the ELK stack for centralized analysis across many machines.

Summarize this post with: