Monday, March 7, 2011

How To Use Apache Log4j Logging API in your Application?

Logging in the context of application development includes inserting statements into the program that provide some kind of output information that is useful to the developer in debuggging process and improve their code or test it’s functionality.
For Logging,Apache has released a project called log4j.To get started with using it in your application.
First download the
latest version here and follow the instructions below:
1. Add log4j’s jar(log4j-x.x.xx.jar where x.x.xx is the version of the release you’ve downloaded) file to your application’s classpath.


2. Create a file named “log4j.properties” and place it in the default package of your source code(the root folder where all your code resides). Copy the following lines in it:

# Log levels
# Uncomment the following line to enable full loggin for every class
#log4j.rootLogger=trace, stdout, R
log4j.logger.com.test.logging=trace, stdout, R


# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n


# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file.
log4j.appender.R.File=./logs/applog.log
log4j.appender.R.MaxFileSize=500KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
# Rolling File Appender layout
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n

Here is a explanation of what the above properties do:
“log4j.logger.xxx” controls the loggers, where xxx is the package for which you want to set log levels.
The line
log4j.logger.com.test.logging=trace, stdout, R
means that you want every class under the com.test.logging package to have a logging level of trace, and output the log to the standard output(the console) using a Console Appender named stdout and to a file using a Rolling File Appender named R.

After that you define the appenders mentioned earlier and set their properties.
The lines
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) – %m%n
define the ConsoleAppender named stdout, set it’s layout to PatternLayout and then assign a pattern for the output.

3. The third and final step is about the code you’ll have to use.
Have a look at the class below:


package com.test.logging;

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


public class LoggingDemo{


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


public static void main(String[] args) {


long time = System.currentTimeMillis();
logger.info("main method called..");
logger.info("another informative message");
logger.warn("This one is 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 + " msecs");


// Exception logging example:
try{
String temp = "Welcome".substring(7);
}catch (Exception e){
logger.error("Error in main() method:", e);
}


}
}


Explanation :

First you have to import org.apache.log4j.Logger and org.apache.log4j.Level(if you want to use the log() method).

Then instantiate a static Logger object using the static method getLogger() and provide your class as an argument.



To log messages through your class, you use the logging methods of the created Logger object.

There are two ways to log messages:


1.Directly, using the methods trace(), debug(), info(), warn(), error() and fatal(), providing the message as an argument.


2.Using the log() method, by providing the level of the message from the Level class and the message to log as arguments.





According to the configuration you provide in the properties file, a message will be logged – or not.
For example, if you set the level to WARN, all messages of level WARN, ERROR and FATAL will be logged and everything else will be omitted.
 In other words, the hierarchy for level is:


TRACE < DEBUG < INFO < WARN < ERROR < FATAL.




 Here’s what you get at the console when you run the LoggingDemo class:


INFO [main] (Main.java:12) - main method called..


INFO [main] (Main.java:13) - another informative message


WARN [main] (Main.java:14) - This one is a warning!


TRACE [main] (Main.java:15) - And a trace message using log() method.


DEBUG [main] (Main.java:19) - Time taken to log the previous messages: 0 msecs


ERROR [main] (Main.java:26) - Error in main() method:


java.lang.StringIndexOutOfBoundsException: String index out of range: -1


at java.lang.String.substring(String.java:1938)


at java.lang.String.substring(String.java:1905)


at com.test.logging.LoggingDemo.main(Main.java:24)

You can learn more by reading the manual located at log4j’s home page: Log4j Manual




Cheers,
Varaprasad.


No comments: