Wednesday 17 September 2014

Archiving Log4j Reports with Runtime Path

    General Log4j Reports will be stored in the path which is specified in the Log4j.properties or Log4j.xml. But in case if one need to pass reports path in runtime(eg: Time Stamped folder names), we have to override the existing Log4j properties. The below example shows how to archive the reports in the folder which will be passed in runtime.

The below method will override the existing properties of Log4j. Here I am overriding file location and I will pass it in runtime.

public void updateLog4jConfiguration(String logFile) {
       Properties props = new Properties();
       try {
           InputStream configStream = getClass().getResourceAsStream( "/log4j.properties");
           props.load(configStream);
           configStream.close();
       } catch (IOException e) {
           System.out.println("Error: Cannot load configuration file ");
       }
       props.setProperty("log4j.appender.FileAppender.File", logFile);
       LogManager.resetConfiguration();
       PropertyConfigurator.configure(props);
   }

This method has to be called with foldername as parameter and before executing your suite(ideally before starting any of your activity).

eg: updateLog4jConfiguration("C:\\Reports\\Report.log");

Below is the Log4j.property file used for the above example:

log4j.rootLogger=WARN
log4j.logger.com.pgx=DEBUG,FileAppender,ConsoleAppender
log4j.appender.FileAppender=org.apache.log4j.FileAppender
log4j.appender.FileAppender.File=./target/logs/report.log
log4j.appender.FileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.FileAppender.layout.ConversionPattern= %d{yyyy-MM-dd HH:mm:ss} %-5p: %m%n
log4j.appender.ConsoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.ConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.ConsoleAppender.layout.ConversionPattern= %d{yyyy-MM-dd HH:mm:ss} %-5p: %m%n

In this example, we changed only log file location but you can even change pattern, layout, log level and any of the values in log4j.properties file.
 
The main trick here is to put following lines in your running code to reset Lo4j with the new values.
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);