Sunday, September 27, 2009

What is Log4j and how can it be configured?

Log4j is a Java based open source logging service by Apache which is available with no cost to the public.The latest edition at the time of writing this post is log4j 2.0 for logging services designed for Java 5 and later.

The insertion of logging comments help in better management of debugging of code specially if the application is distributed and enterprise in nature. The proper usage of logger levels namely DEBUG, INFO, WARN, ERROR and FATAL can help developers analyzing proper functioning of the code.

A simple log4j configuration is explained with a code sample given below, here important is that log4j runtime jar(log4j-1.2.15.jar) is included in the classpath of your application in order to execute the following code:


package com.iqjava.log4j; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; public class ExampleLog4j { static final Logger logger = Logger.getLogger(ExampleLog4j.class); public static void main(String[] args) { BasicConfigurator.configure(); logger.debug("Here goes the debug message"); logger.error("Here goes the error message"); logger.fatal("Here goes the fatal message"); logger.info("Here goes the info message"); logger.warn("Here goes the warn message"); } }


The output of the above code looks as given below:
0 [main] DEBUG com.iqjava.log4j.ExampleLog4j - Here goes the debug message 2 [main] ERROR com.iqjava.log4j.ExampleLog4j - Here goes the error message 2 [main] FATAL com.iqjava.log4j.ExampleLog4j - Here goes the fatal message 2 [main] INFO com.iqjava.log4j.ExampleLog4j - Here goes the info message 2 [main] WARN com.iqjava.log4j.ExampleLog4j - Here goes the warn message


The numbers in the beginning of the output represents time elapsed from the beginning of the execution of the code in milliseconds, thread name, logger level and then log message.

The other logging configuration using log4j is with properties or XML file.Watch out for the next post, it will be related to that.
blog comments powered by Disqus
 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker