Monday, June 24, 2013

Log4j, java library that specializes in logging

Apache Logging Services Project

Log4j, java library that specializes in logging


Log4j is a Java library that specializes in logging. At the time of this writing, its home page is at http://logging.apache.org/log4j/1.2/index.html . The Java library itself is available for download at http://logging.apache.org/log4j/1.2/download.html .  At its most basic level, you can think of it as a replacement for System.out.println's in your code.

Steps to Integrate Log4j with your Java project

2. Add the jar to your project
3. Create a new file 'log4j.properties' in your  project 'src'  and add the contents as follows and save it :
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logs/testlog.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
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
4. Append one line code to integrate Log4j to the class, declare a variable say 'log' as type 'Logger'
 static Logger log = Logger.getLogger(ClassName.class.getName());
'ClassName' is the name of the class that you need to use Log4j for logging.
5. Now you can use 
 log.debug("This is debug message");
  log.info("This is info message");
  log.warn("This is warn message");
  log.fatal("This is fatal message");
  log.error("This is error message");
for debug ,info,warning,fatal and error logs instead of  System.out.println 
Thats It !
For example :


import org.apache.log4j.Logger;
public class Test {
  static Logger log = Logger.getLogger(Test.class.getName());
  public static void main(String[] args) {
   try {
   int i = 1;
   int b = 1 - 1;
   b = i / b;
  } catch (Exception e) {
   log.error("failed", e);
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment