Monday, 29 September 2014

Creating Log file Using Log4j in WebDriver Framework

Tired of sysouts in your scripts !! Well, it makes your Test Scripts execution hell slow.
But you don't even want to omit sysouts from your classes.

Here, log4j (Apache Logging Services) provides you logging library for Java.

Steps to create a Logging Utility in your existing framework :

Step 1 :

Install log4j jar from here and put in lib folder of your project.

Step 2 :

Create a "" file in your config folder.

And write the following code in it :

# Log levels

# Appender Configuration

# Pattern to output the caller's file name and line number
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

# Rolling File Appender

# Path and file name to store the log file

# Number of backup files

# Layout for Rolling File Appender
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n

For all the detailed configuration explanation of log 4j, refer this.



is the location where log file would be created and the maximum size of that log file.

Step 3 :

Now in your test script class, and call the getLogger of Logger class that log4j jar provides.
Here is the sample code :

public class OpenGoogle

  private static Logger logger=Logger.getLogger("OpenGoogle.class"); // write this line 

  public void testOpenGoogle() throws InterruptedException{

   assertTrue(driver.getTitle().contains("Google"));"You have opened"); // use info for printing in log file


Create the logger class object and call the logger which writes in the log file.

Now, replace all the "sysout" statements in your script with "" or any other log 4j configuration according to your requirement.

Doing this, all your sysouts which used to slow down the test execution will reduce and also you will be able to see the full log file once you complete your execution.

And you are done with adding Logging Services in your framework !

Happy Logging !