Adding logs to your java code : log4j

20 Dec
Log4j is a simple and flexible logging framework. In this tutorial you will learn how to configure log4j for your applications. This tutorial uses log4j version 1.2.15.
1.  Add the log4j-1.2.15.jar to the classpath-
import org.apache.log4j.Logger;
2. Next you need to create an instance of Logger class –
static final Logger logger = Logger.getLogger(HelloWorld.class);
It takes one argument the fully qualified class name.
3. Now we need to configure log4j. The simple way to do that is using BasicConfigurator. configure() method. This will log all the messages on the console.
BasicConfigurator.configure();
logger.debug(“Sample debug message”);
logger.info(“Sample info message”);
logger.warn(“Sample warn message”);
logger.error(“Sample error message”);
logger.fatal(“Sample fatal message”);
The full code is –
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args) {
BasicConfigurator.configure();
logger.debug(“Sample debug message”);
logger.info(“Sample info message”);
logger.warn(“Sample warn message”);
logger.error(“Sample error message”);
logger.fatal(“Sample fatal message”);
}
Advertisements

One Response to “Adding logs to your java code : log4j”

  1. greymatter December 20, 2010 at 4:28 pm #

    For any technical questions related to this topic comment below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: