How to add Log4j to java project

This page lists down quick steps to add log4j in the project. On high level, it involves:

  • Add Jar in the build path
  • Add property file in classpath
  • Create static logger and use in your class

Add Jar in the build path

POM.XML
<!-- Add Log4J Dependency -->
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.14</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>

Add property file in classpath

Add following property file in project classpath.

log4j.properties
log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L - %m%n

Create static logger and use in your class

To log a message in any class, create a final static logger and use different logging levels.

class HelloWorld {
	final static Logger logger = Logger.getLogger(classname.class);

	public process(){
		logger.info("Processing task");
		...
		logger.warn("Warning: ...");		
		logger.error("Error encountered");		
		logger.fatal("Fatal error encountered");
	}
}

Version History


Date Description
2013-10-16    Initial Version