Thursday, March 8, 2012

Using Log4J

In this post, I will try to keep things as simple as possible and explain how to use log4j in Java.

1. Create a Java Project in Eclipse, say "Sample"
2. Create a java class with main() method, say Sample.java.
3. Download log4j.jar. I would recommend you to download the latest jar.
4. Have that log4j.jar in buildpath of the project.
5. In the Sample.java, write the following code to include Logging statements:
package com.dwij.sample;

import org.apache.log4j.Logger;

public class Sample {

 public static final Logger LOGGER = Logger.getLogger(Sample.class);

 public static void main(String[] args) {
  LOGGER.info("Simple usage of log4j");
 }
}

6. Run the Sample.java class. Yes, the error you see is expected.
log4j:WARN No appenders could be found for logger (com.dwij.sample.Sample).
log4j:WARN Please initialize the log4j system properly.

7. How to fix this "No appenders issue"?
  • Have a log4j.properties in classpath of the project:
    • Create a file with name "log4j.properties" and have the below content in it:
      • log4j.rootCategory=DEBUG, S
        log4j.appender.S = org.apache.log4j.ConsoleAppender
        log4j.appender.S.layout = org.apache.log4j.PatternLayout
        log4j.appender.S.layout.ConversionPattern = %c{1} [%p] %m%n
    • The logging level can be DEBUG, INFO, ERROR, FATAL
    • "S" in log4j.rootCategory can be any string you want; it is just that you need to give the same string in the other properties (log4j.appender.S, log4j.appender.S.layout, log4j.appender.S.layout.ConversionPattern)
    • I am using ConsoleAppender here because I just want to see the Log statements in the console.
    • ConversionPattern goes something like this:
      • %c{1}  prints the classname that is ran
      • [%p] prints the Log level
      • %m prints the message provided in the log statement in the code
      • %n prints a new line
  • Define your own appender and add it to the Logger instance:
package com.dwij.sample;

import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

public class Sample {
 
 static Appender myAppender;  
 public static final Logger LOGGER = Logger.getLogger(Sample.class);

 public static void main(String[] args) {
  // Define Appender     
  myAppender = new ConsoleAppender(new SimpleLayout());  
  
  LOGGER.addAppender(myAppender);  
  LOGGER.setLevel(Level.ALL); 
 
  LOGGER.info("Simple usage of log4j");
 }
}

8. Run the class, and you should see the below output:
INFO - Simple usage of log4j

In order to keep things simple, I have not included examples which include writing Log statements to Files, etc.

I will add more content, if requested.

No comments:

Post a Comment