Thursday, December 24, 2009

Log4j setup

This is a small help section on setting up log4j in your application and making use of it.
Log4j ofcourse has lot of benefits and is advisable to use to keep tract of the activities in your application.

Following are a few steps to configure log4j

1. Download the jar file from http://logging.apache.org/log4j/1.2/download.html
2. Put the jar file in the folder where you put your libraries (lib folder)
3. Now we need to create a configuration file which can be either a .xml file or a .properties file.
I prefer .properties file as it is easy to create and configure.


I will not go deep into it, as for such things you will find many articles.
I have put a sample .properties file which you can use in you application, just a few changes ofcourse.

log4j.rootCategory=INFO, CONSOLE
# AppFileAppender- used to log messages in the application.log file.
log4j.appender.AppFileAppender=org.apache.log4j.FileAppender
log4j.appender.AppFileAppender.File=../logs/application.log
log4j.appender.AppFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AppFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n

log4j.logger.com.mycompany.myapp=DEBUG,AppFileAppender

The above is goof enough for your application.
(i) The first line is generic, so just paste it.
(ii) Next is the comment, and after that a file appender is defined. Its a log4j thing, so just copy-paste it.
(iii) The next is the log file. By default the log file is created in the config folder of your server. You can change it by specifying the relative path.
(iv) Next 2 lines are regarding patterns, so just copy-paste.
(v) The last line is to link a package to a FileAppender. You can have different files for having logs of different packages. (log4j.logger. is log4j thing, com.mycompany.myapp is the package)

Thats it, you are ready to use log4j in your application. The changes would be in the log file name and the package name.

Now in your classes, make sure you import org.apache.log4j.Logger;
Then create a logger as follows
static Logger logger = Logger.getLogger(WorkerClass.class);

Define this logger immediately after the class and don't keep it in any methods, so its accessible for the entire class.

Then all you do is
logger.info("This is the message to put in the log");
You can use various methods (levels) like debug(), info(), warn(), error(), fatal() etc.
You get more info on these in
http://logging.apache.org/log4j/1.2/manual.html

I guess that was easy. And if it was, then start using log4j and avoid System.out.println in you application. Do it from the start of the application and avoid having to make changes later.

This ofcourse is a very basic of log4j, once you learn more from the link I have given above, you can do lot more things with log4j

No comments:

Post a Comment