Logging with Log4J

It’s assumed that most of the applications developed these days, keep track of their errors and failures via a log file. It turns out to be really handy when it comes to optimizing the app in a later stage.

Project that I’m working these days is also not an exception to it. From its next phase we are planning to integrate error logging. In our case we actually want to externalize all the errors and failures and warnings to a file. So that we may refer it to study the defects and bugs on it that might required to be catered in later versions of the project.

And they say never to use System.out.println to address errors. Simply because it doesn’t give you a mechanism to reference it at a later point unless you manually write it down or get screen shots then and there.

Anyway now we may look at how to get started with error logging in java with popular logging tool, Log4J by Apache Software Foundation (ASF). I’m really sorry if you are not into java probably then this is not for you.

PreRequisites
  • Java
  • An IDE (I use Eclipse so does my project)
  • Log4J (extract the archive file)

Hoping java and eclipse are installed and they are ready to go, now you can open up your eclipse IDE.

  • Create a new Project, name it whatever name you like. (In my case it was Log4JPro).
  • Add a new folder in your project’s root folder (better to name it lib just as a convention).
  • Insert the extracted lib file to the above created folder.
  • Add log4j-xxxxxx.jar file to the classpath of your project.

That’s it now you are almost there. But this actually the most important part of all. What you need to do here is setting up a small configuration file called log4j.properties. This is where you set virtually everything you need to customize with log4j goes in.

There are lots of properties that you can start configuring which will include the type of output you need, the formatting of the report, the maximum size of it (some times), and even the mode of writing (if it’s a file) whether you want to over write the previous file or to append to it and so on and so forth.

Below I’ll just give an example log4j.properties file as a starting point. This configure log4j to give a html output. And already there are more than handful of properties customized on it. And play around with it once you start working with it.

Most importantly this file should reside in the root of your project if you are using eclipse it should be placed in your src (source folder). here is an example properties file.

log4j.rootCategory=,dest3
log4j.category.TestLogging=DEBUG, dest3

log4j.appender.dest2=org.apache.log4j.RollingFileAppender
#log4j.appender.dest2.layout=org.apache.log4j.HTMLLayout
log4j.appender.dest2.Threshold=ERROR
log4j.appender.dest2.File=log4j.log
log4j.appender.dest2.Append=false
log4j.appender.dest2.MaxFileSize=100KB
log4j.appender.dest2.MaxBackupIndex=2

log4j.appender.dest3=org.apache.log4j.DailyRollingFileAppender

log4j.appender.dest3.File=LabLog.html
# Control the maximum log file size
# Rollover log file at the start of each week
log4j.appender.dest3.DatePattern=’.’yyyy-ww

log4j.appender.dest3.layout=org.apache.log4j.HTMLLayout
log4j.appender.dest3.layout.LocationInfo=true
log4j.appender.dest3.layout.Title=ISD Log

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p | %d | %F | %L | %m%n

Below given is an example code and a screen shot of the generated html file of it. Hope you enjoyed it!

/**
* @class LogApp.java
* @author Lonely Coder
* @date 09/30/2008
*/

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LogApp {

private static Logger logger = Logger.getLogger(LogApp.class);

public LogApp() {

}

public static void main(String[] args) {

long time = System.currentTimeMillis();

logger.info(“This is an Information..”);
logger.warn(“This one is just a Warning!”);

logger.log(Level.TRACE, “And a trace message using log() method.”);
long logTime = System.currentTimeMillis() – time;

logger.debug(“Time taken to log the previous messages: ” + logTime
+ ” milli secs”);

try {
String str = “log4j”;
char concat = str.charAt(6);
System.out.println(concat);
} catch (Exception e) {
logger.error(“Error in main() method:”, e);
}

}
}

log4j example log in html

Advertisements