How to use log4j more efficiently in selenium webdriver testing framework

Log4j is the most required logging mechanism for any webdriver testing framework.

We can have a single class, where we can initialize log4j and the invoke a method from that class to get the instance of log4j in each of the other classes.

In the example below you can invoke the createLogger() method from any other class to get the instance of Log4j for example use: private Logger log = Logg.createLogger();

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Logg {

private static Logger _logger;
private static final String fileName = "defaultlog";
private static final String dateAndTimeFormat = "MM-dd-yyyy_hh.mm.ss";
private static final String logProperttFilePath = "./src/main/resources/com/framework/properties/log4j.properties";

static {
/**
* This is the static block which appends the log file name with the
* timestamp to make it unique
*/
 try {
    String dateTime = DateAndTime.getFormattedCurrentDateAndTime(dateAndTimeFormat);
    String FileName = fileName + "-" + dateTime + ".log";
    File file = new File("logs/" + FileName);

    if (file.createNewFile()) {
      Properties props = new Properties();
      props.load(new FileInputStream(logProperttFilePath));
      props.setProperty("log4j.appender.File.File", "logs/"+ FileName);
      LogManager.resetConfiguration();
      PropertyConfigurator.configure(props);
      System.out.println("Property log4j.appender.File.File = logs/"+ FileName);
     }
    } catch (IOException ex) { ex.printStackTrace();
      System.out.print("IO Exception in static method of Logger Class. "+ ex.getMessage());
      System.exit(-1);
   }
}

/**
* This method creates instance of the Logger class coming from log4j jar by
* implementing a singelton
*
* @return _logger - new instance if no instance exist else an existing
* instance if the method is invoked previously
*/
public static Logger createLogger() {
   if (_logger == null) {
       _logger = LogManager.getLogger(Logg.class);
      return _logger;
   } else
  return _logger;
 }
}

Also if you may require dynamic file name in the appender in log4j.xml then we can use the code below. It changes its name according to input file name and current date-time.

public class LogClass {

private static Logger log =  Logger.getLogger(LogClass.class);
private static boolean initializationFlag = false;
private static String fileName;

private static void intializeLogger(){
    log.setLevel(Level.DEBUG);

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date();

    RollingFileAppender appender = new RollingFileAppender();
    appender.setAppend(true);
    appender.setMaxFileSize("1MB");
    appender.setMaxBackupIndex(1);
    appender.setFile(fileName + "_" + dateFormat.format(date) + ".log");

    PatternLayout layOut = new PatternLayout();
    layOut.setConversionPattern("%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");
    appender.setLayout(layOut);

    log.addAppender(appender);
}

public static Logger getLogger(){
    if(initializationFlag == false){
        intializeLogger();
        initializationFlag = true;
        return LogClass.log;
    }
    else{
        return LogClass.log;
    }
}

public static void setFileName(String fileName){
    LogClass.fileName = fileName;
 }
}

Now whenever you want to use logger in your program, Just write these two lines:

LogClass.setFileName(yourFileName);
LogClass.getLogger().debug("hello!!");
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s