My new website on Artificial Intelligence and Machine Learning

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 file and put it into the resources folder.

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

2. Declares the following dependencies


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[]) {"Hi Log4j");
		logger.debug("Hi Log4j");
		logger.error("Hi Log4j, This is an Error");

Project Structure

Log4j Project Structure

Execute the class ( 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.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n