21.8.15

Log4J Configuration


Get the coordinates from maven central repo and add the dependency to your pom

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
Create a file 'log4j.properties' and place it only under 'src/main/resources/' folder in your project, anywhere else, and it will give an error, like No Appenders found.....

This basic configuration would suffice in most cases, add it to the log4j.properties file.
 #---------------
# Root logger option
log4j.rootLogger=INFO, 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}.%M.%L: %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=E:\\ToDelete\\logger.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}.%M.%L: %m%n
#---------------

NB:

  • To use the logger, just declare the class as follows.
    private final static Logger LOGGER = Logger.getLogger(BaseStep.class);

  • And you can start logging as follows.
LOGGER.info("Anything you want");

  • This would create logs in the format Class.Method.LineNo
  • For most part, we can set the logging level to INFO. DEBUG mode will cause log-blindness!
  • Also, if the appender file location [folder] does not exist, it will create it during run-time, provided it has the rights.
  • Although, it is recommended to declare this under each new class that you create, but if you declare it as public, in your base abstract class, then you would not have to declare it everywhere, and should be able to directly use it.


No comments:

Post a Comment