Table of Contents
Enroll in Selenium Training

During the running of test case user wants some information to be logged in the console. Information could be any detail depends upon the purpose. Keeping this in mind that we are using Selenium for testing, we need the information which helps the User to understand the test steps or any failure during the test case execution. With the help of Log4j it is possible to enable loggings during the Selenium test case execution for e.g. let’s say you have encountered a failure in automation test script and it has to be reported in the system. The set of information that you have required to report a bug is :

  • A complete test steps to replicate the scenario
  • Issue, Description of the failure or reason for the failed test case
  • Time stamp for the developers to investigate the issue in detail

Log4j helps us to acheive the above objectives in Selenium Webdriver. When logging is wisely used, it can prove to be an essential tool.

Logging inside the Methods

Logging inside the testcase is very tedious task and sooner or later you will find it boring and annoying. Plus everybody has their own way of writing log messages and messages can be less informative and confusing. So why not make it universal. Writing logs message inside the methods is much helpful way, with that one can avoid lots of confusions, save lot of time and maintain consistency.

Step 1: Set up Log4j

1) Download JAR files of Log4j and Add Jars to your project library. You can download it from here.

  1. Create a new XML file – 'log4j.xml' and place it under the Project root folder.

3) Paste the following code in the log4j.xml file.

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns: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" />




<level value="INFO"/>

<appender-ref ref="fileAppender"/>



Note: After pasting the code make sure that the code is exactly same, as copying from HTML may change some symbols(“) to (?).

Step 2: Set up Static Log class

  1. Create a ‘New Class’ file and name it as 'Log', by right click on the 'utility' package and select New > Class.
  2. All the methods of this log class will be a static, so that it's methods can accessed in any of the class.

Log4j log Class:

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
	public static void startTestCase(String sTestCaseName){"****************************************************************************************");"****************************************************************************************");"$$$$$$$$$$$$$$$$$$$$$                 "+sTestCaseName+ "       $$$$$$$$$$$$$$$$$$$$$$$$$");"****************************************************************************************");"****************************************************************************************");


	//This is to print log for the ending of the test case
	public static void endTestCase(String sTestCaseName){"XXXXXXXXXXXXXXXXXXXXXXX             "+"-E---N---D-"+"             XXXXXXXXXXXXXXXXXXXXXX");"X");"X");"X");"X");


    // Need to create these methods, so that they can be called  
	public static void info(String message) {;

	public static void warn(String message) {

	public static void error(String message) {

	public static void fatal(String message) {

	public static void debug(String message) {


Step 3: Enter logs in Action Keyword Class

Action Keyword Class:

package config;

import java.util.concurrent.TimeUnit;
import static executionEngine.DriverScript.OR;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import utility.Log;

public class ActionKeywords {

		public static WebDriver driver;

	public static void openBrowser(String object){"Opening Browser");
		driver=new FirefoxDriver();

	public static void navigate(String object){"Navigating to URL");
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

	public static void click(String object){"Clicking on Webelement "+ object);

	public static void input_UserName(String object){"Entering the text in UserName");

	public static void input_Password(String object){"Entering the text in Password");

	public static void waitFor(String object) throws Exception{"Wait for 5 seconds");

	public static void closeBrowser(String object){"Closing the browser");


Step 4: Initialize Logs in Driver Script

  1. Once done with logging inside the methods of all the class, just initialize the logs from the main driver script.

Driver Script:

package executionEngine;

import java.lang.reflect.Method;
import java.util.Properties;
import org.apache.log4j.xml.DOMConfigurator;
import config.ActionKeywords;
import config.Constants;
import utility.ExcelUtils;
import utility.Log;

public class DriverScript {

	public static Properties OR;
	public static ActionKeywords actionKeywords;
	public static String sActionKeyword;
	public static String sPageObject;
	public static Method method[];

	public static int iTestStep;
	public static int iTestLastStep;
	public static String sTestCaseID;
	public static String sRunMode;

	public DriverScript() throws NoSuchMethodException, SecurityException{
		actionKeywords = new ActionKeywords();
		method = actionKeywords.getClass().getMethods();

    public static void main(String[] args) throws Exception {
		//This is to start the Log4j logging in the test case
    	String Path_OR = Constants.Path_OR;
		FileInputStream fs = new FileInputStream(Path_OR);
		OR= new Properties(System.getProperties());

		DriverScript startEngine = new DriverScript();

    private void execute_TestCase() throws Exception {
    	int iTotalTestCases = ExcelUtils.getRowCount(Constants.Sheet_TestCases);
		for(int iTestcase=1;iTestcase<=iTotalTestCases;iTestcase++){
			sTestCaseID = ExcelUtils.getCellData(iTestcase, Constants.Col_TestCaseID, Constants.Sheet_TestCases); 
			sRunMode = ExcelUtils.getCellData(iTestcase, Constants.Col_RunMode,Constants.Sheet_TestCases);
			if (sRunMode.equals("Yes")){
				iTestStep = ExcelUtils.getRowContains(sTestCaseID, Constants.Col_TestCaseID, Constants.Sheet_TestSteps);
				iTestLastStep = ExcelUtils.getTestStepsCount(Constants.Sheet_TestSteps, sTestCaseID, iTestStep);
				for (;iTestStep<=iTestLastStep;iTestStep++){
		    		sActionKeyword = ExcelUtils.getCellData(iTestStep, Constants.Col_ActionKeyword,Constants.Sheet_TestSteps);
		    		sPageObject = ExcelUtils.getCellData(iTestStep, Constants.Col_PageObject, Constants.Sheet_TestSteps);

    private static void execute_Actions() throws Exception {

		for(int i=0;i<method.length;i++){

Note: For any explanation on above non commented code, please refer previous chapters.

Logs would produce like this:


Now project would look like this:


Test Suite Execution Engine
Test Suite Execution Engine
Previous Article
Exception Handling
Exception Handling
Next Article
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M A FULL-STACK TEST AUTOMATION ENGINEER. Have passed 16 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently, I am working with RABO Bank as a Chapter Lead QA. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns.
Virender Singh's Photo
Virender Singh

Similar Articles