Share this blog!

How to add the timestamp to the log4j log file




If you are trying to figure out a way to update the log4j log filename dynamically, or more specifically, to add the timestamp to the log file name, this post is for you.






We are going to do this by setting up a system property to store the timestamp and then using it to name the log file. 

So the first task would be to add the following in your Java code. We add it in the class containing the main method and we add it inside a static block so that it will load before the methods.


static {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
    System.setProperty("currenttime", dateFormat.format(new Date()));
} 


A simple hello world will look like below.


import org.apache.log4j.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloWorld {
    static {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
        System.setProperty("currenttime", dateFormat.format(new Date()));
    }

    private static final Logger log = Logger.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        log.info("Hello World!");
    }
}


Then, update the log4j.properties as follows. Note how the ${currenttime} is used in the filename:

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${currenttime}_log.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Cheers!
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment