Log4j Basic Example

Log4j setup is very easy and configurable in minute. Now we try Log4j configuration with log4j property file and other than that jars required for setup

1. Create a log4j.properties file and put it into the resources folder.

# Root logger option
log4j.rootLogger=INFO, stdout
	 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

2. Declares the following dependencies

     <dependency>
	  <groupId>log4j</groupId>
	  <artifactId>log4j</artifactId>
	  <version>1.2.17</version>
     </dependency>

3. To log a message, first, create a final static logger and define a name for the logger, normally, we use the full package class name.

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

Then, logs messages with different priorities, for example, debug, info, warn, error and fatal. Normally, you just need to use debug or error.

package com.javavillage.dozer;
import org.apache.log4j.Logger;

public class Log4jMain {
	private final static Logger logger = Logger.getLogger(Log4jMain.class);

	public static void main(String args[]) {
		logger.info("Hi Log4j");
		logger.debug("Hi Log4j");
		logger.error("Hi Log4j, This is an Error");
	}
}

Project Structure

Log4j Project Structure

Execute the class (Log4jMain.java) with different patterns and log4j levels. Find below result

  2014-10-23 13:06:25 INFO  Log4jMain:9 - Hi Log4j
  2014-10-23 13:06:25 DEBUG Log4jMain:10 - Hi Log4j
  2014-10-23 13:06:25 ERROR Log4jMain:11 - Hi Log4j, This is an Error

Note:  To create specific log file for Log messages use below property changes

# Root logger option
log4j.rootLogger=DEBUG, file
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender

 
log4j.appender.file.File=F:\\App\\javavaillage.log
log4j.appender.file.MaxFileSize=8MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n