"Your time is limited, so don't waste it living someone else's life"

Configure log4j

I will introduce step by step:
1. Download log4j library.
You can easily download the log4j library at link. After download, unzip it into any directory (called D:/log4j).
2. Create a configuration file for your log.
In your project create a new log4j.xml file with the content like:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"

	<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss.SSS} %5p %c{1} - %m%n" />

	<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
		<param name="file" value="log/example.log" />
		<param name="MaxFileSize" value="100KB" />
		<!-- Keep one backup file -->
		<param name="MaxBackupIndex" value="1" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%p %t %c - %m%n" />

		<level value="INFO" />
		<appender-ref ref="consoleAppender" />
		<appender-ref ref="fileAppender" />


Note that you should put the above xml file in the src directory of your project.
3. Create a system property and use the log.
At the beginning of the main method, you create a new system property named org.apache.commons.logging.Log like this snippet:

public static void main(String[] args)
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

At the same time, you can now use the log instance to log anything you want:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MyClass
/** The Constant LOG. */
    private static final Log LOG = LogFactory.getLog(MyClass.class);

     * Launch the application.
    public static void main(String[] args)
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
        LOG.info("Execute main method...");

Happy logging!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: