Log4j Configuration Using Properties File

Log4j Configuration Using Properties File

In this tutorial you will learn how to configure Log4j using properties file.There are mainly two ways to configure log4j externally.We can easily configure the log4j by using a properties file or xml file. The main benefit of this way is once the log statements are in place you can easily control them using the external configuration file without modifying the source code. Let's see how you can configure the log4j configuration by using the properties file.


Steps to create this example

We will develop a Java project using eclipse IDE for this example.Follow the steps mentioned below to implement this example.

Step 1. Download log4j jar

First download the latest version of log4j from here and unzip it in your local drive.

Log4j Configuration Using Properties File

In this tutorial you will learn how to configure Log4j using properties file.There are mainly two ways to configure log4j externally.We can easily configure the log4j by using a properties file or xml file. The main benefit of this way is once the log statements are in place you can easily control them using the external configuration file without modifying the source code. Let's see how you can configure the log4j configuration by using the properties file.


Steps to create this example

We will develop a Java project using eclipse IDE for this example.Follow the steps mentioned below to implement this example.

Step 1. Download log4j jar

First download the latest version of log4j from here and unzip it in your local drive.

Step 2 . Create Java Project

Open Eclipse IDE and create a Java Project and name it. In this example and name it as "LoggingExample".

Log4j Configuration Using Properties File


Step 3 . Add log4j jar file to classpath of the project

Next step is to add the log4j jar which you have downloaded to the "LoggingExample" application by right click on the project in Package Explorer -> Build Path -> Configure Build Path

Log4j Configuration Using Properties File

In the Java Build Path dialogue, go to Libraries tab and Click on Add External JARs button and add the log4j-xxx.jar file by browsing your local drive where log4j jar file is extracted and Click OK.

Log4j Configuration Using Properties File

Now the log4j jar file is available to be used in your application.


Step 4 . Create log4j.properties file

Now create a file named as "log4j.properties" in src package. This file will hold all the configuration settings for log4j for this application. You can create this file by right click on the 'src' -> New -> File ->and then provide the name of the file as log4j.properties and click Finish button.

Log4j Configuration Using Properties File

Now Copy the below line of code to the log4j.properties file you just created.

log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

In any application the first step is to define the log level.The rootLogger is the one that resides on the top of the logger hierarchy. Here we set its level to DEBUG and added the console appender (CA) to it. The console appender can have arbitrary name, here its name is CA.

Log4j logs messages at six different levels. For example, if you have a program that generates lot of warning messages then you can ignore them by setting the log level to ERROR to avoid the log file getting more friendly. The log levels and the priority is as follows,

TRACE < DEBUG < INFO < WARN < ERROR < FATAL

If you specify the log level as WARN, then the INFO, DEBUG and TRACE log level messages will be omitted while the WARN, ERROR and FATAL log level messages will be logged. In our example we have set the log level as DEBUG which means TRACE level logs will not be logged.

log4j.rootLogger=DEBUG, CA

Next comes the appender settings. I have used Console Appender that means application log information will be displayed on the console.You can also use other appenders, like FileAppender, JDBCAppender,SocketAppender,SysLogAppender etc. according to your requirement to route the logging information to appropriate destinations.

log4j.appender.CA=org.apache.log4j.ConsoleAppender

Each appender is associated with layout settings that specifies the format of information that is being logged. We have used PatternLayout for appenders.

log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

In the above code

%5p - Priority of the logging event
%t - Name of the thread that initiated the logging event
%F- File name where the logging issue was requested
%L - line number that caused the logging message to be generated

You can use other layouts such as HTMLLayout, DateLayout, XMLLayout etc.



Step 5 . Create Java Class to test log message

package com.jwt.log;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jDemo {

	static final Logger logger = Logger.getLogger(Log4jDemo.class);
	static final String LOG_PROPERTIES_FILE = "log4j.properties";

	public static void main(String[] args) {
		new Log4jDemo();
		// sample info log message
		logger.info("leaving the main method of Log4JDemo");
	}

	public Log4jDemo() {
		initializeLogger();
		// sample info log message
		logger.info("Log4jDemo - leaving the constructor ...");
	}

	private void initializeLogger() {
		Properties logProperties = new Properties();

		try {
			// load log4j properties configuration file
			logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
			PropertyConfigurator.configure(logProperties);
			logger.info("Logging initialized.");
		} catch (IOException e) {
			logger.error("Unable to load logging property :", e);
		}
		try {
			FileInputStream fstream = new FileInputStream("D:\\textfile.txt");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				System.out.println(strLine);
			}
			in.close();
		} catch (FileNotFoundException fe) {
			logger.error("File Not Found", fe);
			logger.warn("This is a warning message");
			logger.trace("This message will not be logged since log level is set as DEBUG");
		} catch (IOException e) {
			logger.error("IOEXception occured:", e);
		}
	}
}

Output:

 INFO [main] (Log4jDemo.java:38) - Logging initialized.
ERROR [main] (Log4jDemo.java:52) - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the file specified)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(FileInputStream.java:106)
	at java.io.FileInputStream.<init>(FileInputStream.java:66)
	at com.jwt.log.Log4jDemo.initializeLogger(Log4jDemo.java:43)
	at com.jwt.log.Log4jDemo.<init>(Log4jDemo.java:26)
	at com.jwt.log.Log4jDemo.main(Log4jDemo.java:20)
 WARN [main] (Log4jDemo.java:53) - This is a warning message
 INFO [main] (Log4jDemo.java:28) - Log4jDemo - leaving the constructor ...
 INFO [main] (Log4jDemo.java:22) - leaving the main method of Log4JDemo




comments powered by Disqus