• Selenium Video Tutorials

Selenium - Log4j Logging



Selenium Webdriver can be used for logging information during test execution. The logging is mainly used to extract information about how the execution took place.

Logging helps to enhance any application by supplying data on the features of the application which are working or not working. Thus logging is important to raise the quality of the application and troubleshoot issues.

What is Log4j?

Log4j is an open-source Java based framework primarily used for logging information. It is a straightforward, sound, and fast framework. The Log4j has to be configured using a configuration file like Log4j.xml file, Log4j.properties file, yaml or JSON file, and so on in the form of key value pairs. Log4 is a part of Apache Logging Services.

Components of Log4j

The components of Log4j are listed below −

  • Loggers

  • Appenders

  • Layouts

Loggers

The Loggers contain all the important logging information produced by using the Log4j framework. The basic components of Loggers are −

  • Object of Logger class.

  • Log Levels − The log levels help to get the log messages. The log levels are - ALL which logs all every information, ERROR which logs only error information which may pause the execution, WARN which logs only error information which may pause the execution but not fatal, DEBUG which logs information required for debugging, INFO which logs how the application is responding, TRACE which logs the most elaborate logging information, and FATAL which logs picky information of the application which may result in crash in the application.

Appenders

The appenders get the information from the Loggers and outputs it to another file or storage. The appenders are - FileAppender which writes the logging information to another file, RollingFileAppender which works similar to FileAppender with limit to the file size, once the file size exceeds, the remaining logging information is captured in another new file created by the appender, DailyRollingFileAppender is used to provide the interval in which logging information is to be captured in a file, and ConsoleAppender which writes the logging information in the console.

Layout

The layouts are used to set the format of the log files. The layouts are - Pattern Layout, HTML Layout, XML Layout, and so on.

Prerequisites for Log4j Logging

  • Install Java(version above 8) in the system and check if it is present with the command: java -version. The java version installed will be visible if installation has been completed successfully.

  • Install maven in the system and check if it is present with the command: mvn -version. The maven version installed will be visible if installation has been completed successfully.

  • Install any IDE like Eclipse, IntelliJ, and so on.

  • Save the pom.xml with all the dependencies and update the maven project

Steps for Log4j Logging

Step 1 − Create a maven project and add the proper dependencies to the pom.xml file for the below items −

Step 2 − Create a configuration file - log4j.xml or loj4j.properties file. Here, we will provide the settings. In our project, we had created a file named log4j2.properties file under the resources folder.

Selenium Log4j Logging 1

Step 3 − Create a test class where we will create an object of the Logger class and incorporate the log statements. Run the project and validate the results.

Example

package Logs;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LoggingsInfo {

   // object of Logger class
   private static Logger logger = LogManager.getLogger(LoggingsInfo.class);

   public  static void main(String args[]){

      System.out.println("Execution started: ");

      // logging messages
      logger.info("This is for information");
      logger.error("This is for error information");
      logger.warn("This is for warning information");
      logger.fatal("This is for fatal information");

      System.out.println("Execution done: ");
   }
}

Configurations in log4j2.properties file.

name=PropertiesConfig
property.filename = logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/LogsGenerated.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=Logs
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Dependencies in pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
   
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>

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

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

   </dependencies>
</project>

Output

Execution started: 
[INFO ] 2024-03-21 16:15:08.431 [main] LoggingsInfo - This is for information
[ERROR] 2024-03-21 16:15:08.432 [main] LoggingsInfo - This is for error information
[WARN ] 2024-03-21 16:15:08.432 [main] LoggingsInfo - This is for warning information
[FATAL] 2024-03-21 16:15:08.432 [main] LoggingsInfo - This is for fatal information
Execution done: 

Process finished with exit code 0

Along with that a file LogsGenerated.log get generated within the log folder within the project containing the logging information as the console output.

Selenium Log4j Logging 2

We can also change the logging level configuration to trace by updating the rootLogger.level = trace and logger.file.level = trace in the log4j2.properties file.

Updated configuration log4j2.properties

name=PropertiesConfig
property.filename = logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/LogsGenerated.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=Logs
logger.file.level = trace
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = trace
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Example

package Logs;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LoggingsInfo {

   // object of Logger class
   private static Logger logger =
   LogManager.getLogger(LoggingsInfo.class);

   public  static void main(String args[]){
      System.out.println("Execution started: ");

      // logging messages
      logger.trace("This is for trace information");
      logger.info("This is for information");
      logger.error("This is for error information");
      logger.warn("This is for warning information");
      logger.fatal("This is for fatal information");

      System.out.println("Execution done: ");
   }
}

Output

[TRACE] 2024-03-21 16:25:08.354 [main] LoggingsInfo - This is for trace information
[INFO ] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for information
[ERROR] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for error information
[WARN ] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for warning information
[FATAL] 2024-03-21 16:25:08.356 [main] LoggingsInfo - This is for fatal information
Execution done: 

Process finished with exit code 0

Along with that the file LogsGenerated.log that got generated within the log folder within the project was updated with the trace information.

Selenium Log4j Logging 3

In both the above cases, we had overwritten the log file, however, we can append logs to the log file by adding the configuration: appender.file.append=true to the log4j2.properties file.

Also, to disable logging information in the console and to the log file, we have to update the log4j2.properties with the logger.file.level = off and rootLogger.level = off.

This concludes our comprehensive take on the tutorial on Selenium - Log4j Logging. We’ve started with describing Log4j and its components, prerequisites to set up Log4j, and walked through steps to create Log4j with an example illustrating how to use it along with Selenium. This equips you with in-depth knowledge of the Log4j. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.

Advertisements