Configure Log4j.properties in java

As discussed in the previous tutorial, it is always recommended to use configuration files. The most widely used configuration files are using log4j.properties file and log4j.xml configuration file.

In this tutorial, we will see how to configure log4j with properties file using java.

Step 1: Download Log4j jar file. You can download from Apache Log4j

Step 2: Create a simple class named 'LoggerExample.java'

Step 3: Create log4j.properties file

Step 4: Attach log4j dependency to class path.

We will create few methods in the class to see different logging levels printing on the console. The below is the updated class 'LoggerExample.java'

package com.log.test;

import org.apache.log4j.Logger;

public class LoggerExample {

	 // get a logger instance
	public static Logger logger = Logger.getLogger(LoggerExample.class);

	public void testLoggerDebug() {
		logger.debug("Hello.. im in Debug method");
	}

	public void testLoggerInfo() {
		logger.info("Hello.. im in Info method");
	}

	public void testLoggerWarn() {
		logger.warn("Hello.. im in Warn method");
	}

	public void testLoggerError() {
		logger.error("Hello.. im in Error method");
	}

	public void testLoggerFatal() {
		logger.fatal("Hello.. im in Fatal method");
	}

	public static void main(String[] args) {
		LoggerExample example = new LoggerExample();
		example.testLoggerDebug();
		example.testLoggerInfo();
		example.testLoggerWarn();
		example.testLoggerError();
		example.testLoggerFatal();
	}
}

Log4j allows logging requests to print statements to multiple destinations. Here an output destination is called an appender. Currently, appenders exist for the ConsoleAppender appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.

and FileAppender appends log events to a file. We also have RollingFileAppender which extends FileAppender to backup the log files when they reach a certain size. The default maximum size of a file is 10MB.

Now let us see the sample Log4j.properties file.

#### Using only one appenders, i.e. to log to console  
#Set logging level
log4j.rootCategory=debug, console
  
#### Appender which writes to console  
log4j.appender.console=org.apache.log4j.ConsoleAppender  
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{MM-dd-yyyy HH:mm:ss} %F %-5p [%t] %c{2} %L - %m%n

In the same way, we can also create an other appender to log to an external file. Log files will give us certain information about when a program was started, how much time it took to start the server, where errors are coming from, how often errors return, and how they are etc. We can have access to logs and should monitoring when ever required.

Now after adding the second appendar to log4j.properties file, It should look like below:

# Use two appenders, one to log to console, another to log to a file  
#Set level
log4j.rootCategory=debug, console, file  
  
# Appender which writes to console  
log4j.appender.console=org.apache.log4j.ConsoleAppender  
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{MM-dd-yyyy HH:mm:ss} %F %-5p [%t] %c{2} %L - %m%n
  
# Appender which writes to a file  
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=log4j-application.log
  
# Defining maximum size of a log file
log4j.appender.file.MaxFileSize=5mb  
log4j.appender.file.MaxBackupIndex=5  
log4j.appender.file.layout=org.apache.log4j.PatternLayout  
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %5p [%t] %c{1}:%L - %m%n 

In the above log4j.properties file, PatternLayout lets the user to specify the output format according to conversion patterns. The below are the few patterns that are mostly used:

# Each conversion specifier starts with a percent sign (%) and is followed by optional format modifiers and a conversion character
# %d{dd MMM yyyy HH:mm:ss,SSS} - Used to output the date of the logging event, we can specify date format specifier enclosed between braces
# %F - Used to print file name
# %-5p means the priority of the logging event should be left justified to a width of five characters.
# %t - Used to output the name of the thread that generated the logging event.
# %L - Used to output the line number from where the logging request was issued.
# %m - Used to output the application supplied message associated with the logging event.
# %M - Used to output the method name where the logging request was issued.
#%d{ISO8601}Formats a Date in the format "yyyy-MM-dd HH:mm:ss,SSS" for example "1999-11-27 15:49:37,459".
#%d{HH:mm:ss,SSS} Used to output the date of the logging event. If no date format specifier is given then ISO8601 format is assumed by default.

After executing the above program, the output should look like below:

07-30-2015 01:10:50 LoggerExample.java DEBUG [main] test.LoggerExample 12 - Hello.. im in Debug method
07-30-2015 01:10:50 LoggerExample.java INFO  [main] test.LoggerExample 17 - Hello.. im in Info method
07-30-2015 01:10:50 LoggerExample.java WARN  [main] test.LoggerExample 22 - Hello.. im in Warn method
07-30-2015 01:10:50 LoggerExample.java ERROR [main] test.LoggerExample 27 - Hello.. im in Error method
07-30-2015 01:10:50 LoggerExample.java FATAL [main] test.LoggerExample 32 - Hello.. im in Fatal method

The most common error that you come across when configuring Log4j is "No appenders could be found for logger"

log4j:WARN No appenders could be found for logger (com.log.test.LoggerExample).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

To resolve the above issue, you need to make sure the configuration file is placed in an appropriate location.

Hope this helps you. Please feel free to comment your queries.

Log4j Tutorials: 

Comments

When ever you commit files, cvs will invoke this program and allow you to provide comments about the change you are making.

Where should we keep the configuration file? How can I decide its location?

If you are having different packages, you can keep the properties file inside the package itself. It works for me in that manner. :)

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.