10l. Advanced WebDriver – Using Log4j Part 2

This is a continuation of the article, ‘Using Log4j Part 1’ and hence, I suggest that you read part 1 before proceeding any further to get a grip on what’s happening.

Scenario

  1. Configure Log4j.properties file,
    • Log level – DEBUG
    • Loggers – rootLogger and SeleniumTestLogger
    • Appender – RollingFileAppender
    • Layout – PatternLayout
  2. Write a JUnit4 test case, ‘Log4jTest.java’,
    • Open Chrome browser.
    • Navigate to the demo site
    • Create an instance for the Logger class
    • Log “opening selenium-practice-site” to test.log
    • Locate ‘Bicycle’ checkbox by name and click on it
    • Log “Bicycle checkbox selected”
    • Locate ‘Magazines’ radio button using cssSelector and select it
    • Log “Magazines radio button clicked”
    • Log “Log4jTest executed successfully”
  3. Verify,
    • Eclipse IDE console output screen
    • JUnit pane for success result
    • log and test.log files and check if logs are updated as expected

Now that our plan for the day is out of our way, let’s get coding.

Step 1: Configuring the property file

Let’s first see what code goes into the Log4j’s configuration file, Log4j.properites file.

#Root logger options
log4j.rootLogger=debug,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=E:\\Selenium\\resources\\system.log
log4j.appender.file.maxFileSize=900KB
log4j.appender.file.maxBackupIndex=3
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L \u2013 %m%n
log4j.appender.file.Append=false
#Application Logs
log4j.logger.SeleniumTestLogger=DEBUG, dest
log4j.appender.dest.File=E:\\Selenium\\resources\\test.log
log4j.appender.dest=org.apache.log4j.RollingFileAppender
log4j.appender.dest.maxFileSize=500KB
log4j.appender.dest.maxBackupIndex=6
log4j.appender.dest.layout=org.apache.log4j.PatternLayout
log4j.appender.dest.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest.Append=false

Is it looking all Greek and Latin to you right now? No worries, let us look at it one line at a time.

We are going to have two loggers,

  1. rootLogger – deals with system generated logs and outputs them to system.log file and
  2. SeleniumTestLogger – deals with the logs generated as a result of the commands manually inserted in code by the user and are outputted to test.log file

Both these loggers will have a RollingFileAppender and PatterLayout.

log4j.rootLogger=debug,file – Log level is specified as debug and file is used as an identifier to refer to this particular logger.

log4j.appender.file=org.apache.log4j.RollingFileAppenderRollingFileAppender is the type of appender used and it appends the specified file to a maximum size.

log4j.appender.file.File=E:\\Selenium\\resources\\system.logFile is used to specify the location of the file where the logs are to be saved, i.e. the destination.

log4j.appender.file.maxFileSize=900KB – one file can store data up to a maximum of 900KB, after which a new file with the same name is created. The older file will be added as an index to the latest one.

log4j.appender.file.maxBackupIndex=3 – a maximum of three files will be saved as backup.

log4j.appender.file.layout=org.apache.log4j.PatternLayoutPattern layout is used for formatting the generated logs.

log4j.appender.dest.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n – this is the conversion pattern used to generate the layout.

Sample test log generated is as follows (snippet),

16/05/2019 22:18:17 SeleniumTestLogger Log4jTest executed successfully

  • dd/MM/yyyy – date
  • HH:mm:ss – time of execution
  • %c – name passed as an argument to the Logger instance is printed
  • %m%n – Log message

log4j.appender.file.Append=false – Setting this property to false will create a new file instead of updating the existing one.

log4j.logger.SeleniumTestLogger=DEBUG, dest – Log level is debug and dest is the identifier used here.

log4j.appender.dest.File=E:\\Selenium\\resources\\test.logdest identifier’s file location is specified with the help of ‘File’.

Other properties are similar to what we already discussed and hence are self-explanatory.

Step 2: Writing the test case

Below is the test case, ‘Log4jTest.java’, covering all the requirements as set out in the scenario discussed in the beginning.

package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Log4jTest {
	// Declaring variables
	private WebDriver driver;
	private String baseUrl;
	private Logger log;

	@Before
	public void setUp() throws Exception {
		// System property set up for Chrome driver
		System.setProperty("webdriver.chrome.driver", "browser-drivers\\chromedriver.exe");
		// Create a new instance for the class ChromeDriver
		// that implements WebDriver interface
		driver = new ChromeDriver();
		// Implicit wait for 5 seconds
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		// Assign the URL to be invoked to a String variable
		baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
		
		// Create a logger instance and pass Class name which is Log4jTest in this case
		log = Logger.getLogger("SeleniumTestLogger");
	}
	
	@Test
	public void testElementsWithLogging() throws Exception {
		// Open baseUrl in Chrome browser window
		driver.get(baseUrl);
		log.debug("opening selenium-practice-site");
		
		// Locate 'Bicycle' checkbox using name
		WebElement bicycle = driver.findElement(By.name("vehicle1"));
		// Click the checkbox
		bicycle.click();
		log.debug("Bicycle checkbox selected");
		
		// Locate 'Magazines' radio button using cssSelector
		WebElement magazinesRadioBtn = driver.findElement(By
			.cssSelector("input[value='Magazines']"));
		// Click the radio button
		magazinesRadioBtn.click();
		log.debug("Magazines radio button clicked");
		log.debug("Log4jTest executed successfully");
		
	} // End of @Test

	@After
	public void tearDown() throws Exception {
		// Close the Firefox browser
		//driver.close();
		System.out.println("Closing the driver");
	}
}

import org.apache.log4j.Logger; – Logger package is imported.

log = Logger.getLogger("SeleniumTestLogger"); – Create an instance named, log for the Logger class and pass “SeleniumTestLogger” as the argument.

log.debug("opening selenium-practice-site"); – This statement will log the message given in double quotes in DEBUG level.

Clear comments are given for every line of code making it easy to follow. As you can see, log statements in debug level are inserted at various points of the test case.

Step 3: Verification

Eclipse IDE output screen shows,

  • ‘Console’ without any errors and
  • ‘JUnit’ pane with a green bar showing successful execution of the test case

JUnit Output

  • Both system.log and test.log files are updated as expected with system logs and user coded logs with timestamp as specified in the properties file layout.

Generated Test.log file

Code files, log files, and related JARs are placed in the GitHub repo as always. I hope you have now understood how to take advantage of one of the popular loggers in our test cases automated with Selenium WebDriver.

Have a nice day!

<< 10k. Advanced WebDriver – Using Log4j Part 1

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.