Simple Log4J Example Tutorial

Logging is very important in our project, it will record all activity include of info, error, debug, etc . With a good logging, we can trace when we get problem and fix it immediately. Now, I use Log4J as my logging framework, I will show you a simple Log4j example in this article . When you want to use Log4J, you have to make a file (whatever between .properties or .xml) that will be format your logging message. You can customize your logging properties, this is what I have :

#log4j.properties
log4j.rootLogger=DEBUG,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n</pre>

Anyway, you have to remember logging order in log4j :
1. FATAL
2. ERROR
3. WARNING
4. INFO
5. DEBUG
6. TRACE

For example, if you put INFO as your root logger, all DEBUG and TRACE logging type will not be shown, so please be careful with this. Where is the place to put this properties? If you are using Maven, you can put properties file in src/test/resources, But if you are not, Log4j will automatically search properties on the root of your source folder. So how do I use it? simple, I make a simple class like this :

package com.kusandriadi.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log4JExample {

	private static Logger log = LoggerFactory.getLogger(Log4JExample.class);

	public static void main(String[] args) {
		log.info("info log example...");
		log.debug("debug log example...");
	}
}

if you use my log4j properties, it will give us output like this :


2012-11-29 00:18:18,198 [Log4JExample] INFO com.kusandriadi.log.Log4JExample:11 - info log example...
2012-11-29 00:18:18,203 [Log4JExample] DEBUG com.kusandriadi.log.Log4JExample:12 - debug log example...

example code above using main class, so easy and simple right? if you using maven, here are the dependency :

<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.2</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.2</version>
	<scope>test</scope>
</dependency>

regards,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.