Wednesday, March 18, 2015

Log4j

Most java coders are familiar with log4j setup, but in case you need an example here is one.

This log4j properties file is placed in the classpath of the application.  For a maven setup, which I prefer, place the log4j.properties file in src/main/resources directory of your java project.

# log4j properties file
log4j.rootLogger=DEBUG, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${user.home}/application.log
log4j.appender.file.MaxFileSize=50MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss:SSS} %m%n


This specific setup will write to a log file located in the user's home directory.  I like this solution because it is operating system independent and file system structure independent.

For maven setup you will need to add the log4j dependency to your pom.xml.

<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>

</dependency>

Then create the logger class object in your java class that you want to add logging to.  Make sure this is the first line in your class, right after you define the class name.

public class ApplicationLoader {
  
    private final static Logger LOGGER = Logger.getLogger(ApplicationLoader.class);



To log something just do this:

LOGGER.info(ApplicationLoader.class.getName() + " [ApplicationLoader] : begin");


1 comment: