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 "log4j.properties" file in your config folder.

And write the following code in it :


# Log levels
log4j.rootLogger=INFO,CONSOLE,R

# Appender Configuration
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

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

# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender

# Path and file name to store the log file
log4j.appender.R.File=../logs/LogFile.log
log4j.appender.R.MaxFileSize=1000KB

# Number of backup files
log4j.appender.R.MaxBackupIndex=2

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


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

Here,

log4j.appender.R.File=../logs/LogFile.log
log4j.appender.R.MaxFileSize=1000KB

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{

   driver.get("https://www.google.co.in/");
   assertTrue(driver.getTitle().contains("Google"));
   logger.info("You have opened Google.com"); // 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 "logger.info" 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 !