How to Create Log Details For Java Selenium Program?

Create Log Details For Java Selenium Program: How do you create log details for Java Selenium Program?

When writing an automation script, we face a common situation when sometimes our scripts fail, or while running our automation script, we want some information that needs to be logged in the console. At that time, if we didn’t have any logs, it was very difficult to debug the failure, and we may need to spend a lot of time debugging and fixing the failure. So, it’s recommended to use the log in any scripting language.

How to Create a Log?

Keeping this in mind, while writing the selenium automation script for testing, we use Log4j, which helps us understand which test steps got passed and which failed during the execution.

What is Log4j?

Log4j is an open-source logging framework that Apache creates. Using it, we can store our data related to logs without touching the application. With this, we can also easily find the selenium automation flow logs to trace the application failure easily.

For example, if your Selenium automation scripts fail and you need to report that in the system, you need some set of information like:

  • Complete test steps or test scenarios
  • Issues, Description of failures, and reason behind the failed test case.
  • Time detail for developers to investigate the issue in detail

Components Of Log4j:

There are mainly 3 components available in Log4j that are:

  • Loggers
  • Appenders
  • Layouts

Let us discuss each of them one by one in detail:

Loggers: This is mainly used for logging information in the script. To successfully use logger in the framework, we need to take care of the following things:

  • To use the automation framework, we have to create an object of the logger class.
  • After creating the object, we need to define the log level. Log4j, have 5 different log level, that is:

All – This level of logging will log everything and is intended to turn on all logging.
DEBUG – It saves the debugging information and is most helpful to debug an application.
INFO – It prints an informational message highlighting the application’s progress.
WARN – It designates potentially harmful situations.
ERROR – It designates error events that might allow the application to continue running.
FATAL – It designates very severe error events that will presumably lead the application to crash
OFF – It is intended to turn off logging.

Appenders: In log4j, the output destination is called the appender. It allows the destination where we want to save the logs. Following are a few types of Appenders
ConsoleAppender logs to standard output
File appender prints logs to some file
Rolling file appender to a file with a maximum size

Layouts: This is used for styling the file where you can print and save the log information.

How to Use Log4j in Selenium WebDriver?

  • Download the Log4j jar file from this link [https://logging.apache.org/] and add it to your project. This is all about the configuration of Apache POI with Eclipse.
  • Create a new XML file – log4j.xml and place it under the Project root folder.
  • Paste the following code in the log4j.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="fileAppender" class="org.apache.log4j.FileAppender">
        <param name="Threshold" value="INFO" />
        <param name="File" value="logfile.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
        </layout>
    </appender>
    <root>
        <level value="INFO" />
        <appender-ref ref="fileAppender" />
    </root>
</log4j:configuration>

If you see the xml file, then you will get a line:

<param name="File" value="ExecutionLog.log" />

The above line tells the compiler where the logs will be appended. So ensure the mentioned file “logfile.log” is in your project root directory.

Let us take an example to understand how to implement a log in your automation framework.

1. Create a logFile: Log.java

package utility;
import org.apache.log4j.Logger;
public class Log 
{
   // Initialize Log4j logs
   private static Logger Log = Logger.getLogger(Log.class.getName());// 
   // This is to print log for the beginning of the test case, as we usually run so many test cases as a test suite
   // Need to create these methods, so that they can be called   
   public static void info(String message) 
   {
      Log.info(message);
   }
   public static void warn(String message) 
   {
      Log.warn(message);
   }
   public static void error(String message) 
   {
      Log.error(message);
   }
   public static void fatal(String message) 
   {
      Log.fatal(message); 
   }
   public static void debug(String message) 
   {
      Log.debug(message);
   }
}

How to Implement Log In Your Program?

package automationFramework;
// Import Package Log4j.*
import org.apache.log4j.xml.DOMConfigurator;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import pageObjects.*;
import utility.*;
import appModules.*;
public class Log4j_Logging_TC 
{
   private static WebDriver driver = null;
   public static void main(String[] args) throws Exception 
   {
      // Provide Log4j configuration settings
      DOMConfigurator.configure("log4j.xml");
      Log.startTestCase("Selenium_Test_001");
      ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData,"Sheet1");
      Log.info(" Excel sheet opened");
      driver = new FirefoxDriver();
      Log.info("New driver instantiated");
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      Log.info("Implicit wait applied on the driver for 10 seconds");
      driver.get(Constant.URL);
      Log.info("Web application launched");
      SignIn_Action.Execute(driver);
      System.out.println("Login Successfully, now it is the time to Log Off buddy.");
      Home_Page.lnk_LogOut(driver).click();
      Log.info("Click action is perfomred on Log Out link");
      driver.quit();
      Log.info("Browser closed");
      ExcelUtils.setCellData("Pass", 1, 3);
      Log.endTestCase("Selenium_Test_001");
   }
}

Once your execution is complete, you can check the log file “logfile.log,” which is in your project root folder for the log details.

package com.selenium.basics;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CreateLog 
{
   public static void main(String[] args) 
   {
      Logger log=Logger.getLogger(CreateLog.class);		
      WebDriver driver=new FirefoxDriver();
      log.info("WebDriver Object Created");
      driver.get("http://www.google.com");
      log.info("Google Site Opened");
   }
}

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment