All IT Courses 50% Off
Selenium Tutorials

Download, Install, and Use of Log4j with Example using Selenium

What is log4j?

Log4j is a simple, reliable, fast, and flexible login framework which is written in java. It is highly configurable through external configuration files at run time. We configure Log4j through configuration files which can be XML files, properties file, JSON file, etc. Log4j has been ported to languages like C, C++, Perl, Python, C#, etc. It is used for small to large scale projects in Selenium Automation.

Why use Log4j?

  • Log 4j is an open-source tool
  • Log 4j is used for small and large scale projects
  • With Log4j, it is possible to store the flow details in a file or database.
  • Rather than using SOPL statements, we use log statements in the code to know the status of the project while executing.

Log4j main components:

  1. Loggers: It is used to log the information. Following steps needed to be performed to implement loggers into the project.
    • Create an instance for logger class: Logger class is a Java-based utility that has already implemented generic methods to use log4j.
    • Define the Log4j level: There are five kinds of log levels
      1. All – It will log everything at this level.
      2. DEBUG – It will print the debugging information and is helpful in the development stage
      3. INFO – It will print an informational message that highlights the progress of the application
      4. WARN – It will print faulty information and unexpected system behavior
      5. ERROR – It will print an error message that allows the system to continue
      6. FATAL – It will print system fatal information that is causing the application to crash
      7. OFF – No logging.
  2. Appenders: It is used to deliver the logging information to the destination like database, file, console, etc. The following are the types of Appenders.
    1. ConsoleAppender logs to a standard output
    2. File appender will print logs to some file
    3. The rolling file will append to a file with a maximum size

Note: We can call the appender with any name in log4j properties.

  1.  Layouts: It is used for formatting logging information in different styles.

To handle logging activities the Logger class provides different methods. For obtaining a Logger Object it provides two static methods.

static.PNG

How log4j is configured?

We have to decide which appender to implement if we want to configure log4j. Accordingly, we will set the parameters of the appender.

  • We will use the DEBUG level and RollingFileAppender parameters.
  • We will use two logs,
    • root logger: It will write all system-generated logs in file name i.e. Testing.logs
    • application logger: It will write the information that is generated by manual commands in code into the file name i.e. Manual.logs
  • The Layout will be PatternLayout

Root logger

log4j.rootLogger=DEBUG,files
log4j.appender.files=org.apache.log4j.RollingFileAppender
log4j.appender.files.File=E:\\Testing\\src\\Testing.logs
log4j.appender.files.maxFileSize=800KB
log4j.appender.files.maxBackupIndex=6
log4j.appender.files.layout=org.apache.log4j.PatternLayout
log4j.appender.files.layout.ConversionPattern=%d{ABSOLUTE} %5p %c<strong>{1}</strong>:%L - %m%n
log4j.appender.files.Append=false

Application Logs

log4j.logger.devpinoyLogger=DEBUG, dest2
log4j.appender.dest2=org.apache.log4j.RollingFileAppender
log4j.appender.dest2.maxFileSize=800KB
log4j.appender.dest2.maxBackupIndex=6
log4j.appender.dest2.layout=org.apache.log4j.PatternLayout
log4j.appender.dest2.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest2.File=E:\\Testing\\src\\ManualTest.logs
log4j.appender.dest2.Append=false

From the above example, we have configured log4j to log in two different files Testing.logs and ManualTest.logs.

  • In the above files and dest2 are the two identifiers.
  • “File” is used to give file name where the logs will be saved
  • “maxFileSize” is used to configure the maximum size of the log file. When the file reaches this maximum size it will create a new file with the same name and the old file name will be added as an Index to it.
  • “maxBackupIndex” is used to configure the maximum number of files to be backup.
  • “layout” is used to set the log file format.
  • “Append” is used to set append function. If it is set to false, then every time it will create a new file rather than using old file for logging

How log4j is used within the script?

In the below code, we have used “log” as a reference variable referencing getLogger method of Logger Class

Logger log = Logger.getLogger("developmentLogger");
Use "log" referencing variable and debug the method to log the information.
log.debug("--information--");

Steps to use Log4j with Selenium

Step 1: Launch the Eclipse and create a New Project > log4j_test

Step 2: Right-click on src > Select Build Path > Configure Build Path

log4j libraries

Step 3: Click on Libraries Tab and Add Log4j libraries. You can download the Log4j libraries from below URL

https://logging.apache.org/log4j/1.2/download.html

Step 4: Unzip the log4j file and add the log4j libraries.

log4j libraries

Step 5: Create a new file 

  1. Right-click on src folder > Select New > Select Other > General >File.
  2. Enter the File name as log4j.properties
  3. Click on Finish button
log4j properties

Create two more files and names as Testing.logs and ManualTest.logs. These two files will have all the logs created by the system and manually logged statements.

log4j properties

Step 6: Copy the entire configuration in log4j.properties

#Root logger
log4j.rootLogger=DEBUG,files
log4j.appender.files=org.apache.log4j.RollingFileAppender
log4j.appender.files.File=D:\\selenium_log4j\\log4jDemo\\src\\Testing.logs
log4j.appender.files.maxFileSize=800KB
log4j.appender.files.maxBackupIndex=6
log4j.appender.files.layout=org.apache.log4j.PatternLayout
log4j.appender.files.layout.ConversionPattern=%d{ABSOLUTE} %5p %c<strong>{1}</strong>:%L - %m%n
log4j.appender.files.Append=false

#Application Logs
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=800KB
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:\\selenium_log4j\\log4jDemo\\src\\ManualTest.logs
log4j.appender.dest1.Append=false

Step 7: Create a Main Class

  1. Right-click on src > New > Class
  2. Enter the Class name(Log4jDemo) and click on Finish button
package log4j_test;

import java.util.concurrent.TimeUnit;

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

public class Log4jDemo {

public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","F:\\drivers\\geckodriver.exe");  
     WebDriver driver = new FirefoxDriver();

        Logger log = Logger.getLogger("devpinoyLogger");
        
        driver.get("https://www.google.co.in");
log.debug("opening webiste");
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

       driver.findElement(By.name("q")).sendKeys("Selenium");

       log.debug("Entered Selenium Keyword");

}
}

We create system-level logs using Logger.getLogger(“devpinoyLogger”) 

We store data into Manual.log by using log.debug method 

Step 8: Run the script. Open the location of ManualTest and Testing logs to check logging data.

XML File Configuration with Log4j

With the XML configuration file, we can also configure the log4j logging system. Below are the steps to configure the log4j libraries with XML.

XML File Configuration with Log4j

1. All the attributes between <appender> and </appender> are appender component properties.
2. name: fileAppender and Rolling file appender is the value, which means using RollingFileAppender as an output type.

Download, Install, and Use of Log4j with Example using Selenium

3. name:File and file point value location where we need to store the output.

Download, Install, and Use of Log4j with Example using Selenium

4. layout tag state what kind of the layout we want in the output (here pattern layout)

Download, Install, and Use of Log4j with Example using Selenium

5. priority tag defines the priority level

Download, Install, and Use of Log4j with Example using Selenium

Integration of XML with Log4j

1. Create a Java class and create an object for logger class using getLogger() method from Logger class.

Download, Install, and Use of Log4j with Example using Selenium

2. Load the xml file using configure method from the DOMConfigurator class

Download, Install, and Use of Log4j with Example using Selenium

3. Log a message to the file

Download, Install, and Use of Log4j with Example using Selenium

Complete program for XML integration with log4j

Download, Install, and Use of Log4j with Example using Selenium

Conclusion:

  • Log4j is a simple, reliable, fast, and flexible login framework which is written in java language.

Facebook Comments
Tags

Related Articles

Back to top button
Close
Close

Get Selenium Training Online
Course Now at 50%OFF!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys will use this information to be in touch with you for providing updates.