Simple Log4j Configuration in Java

Introduction

We will see here an example on simple log4j configuration in Java. The purpose of inserting log statements into the code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is often the case for distributed applications.

Features of Log4j

  • We can enable logging at runtime without modifying the application binary.
  • We can control the behavior of logging by editing only the configuration file, no need to touch the application binary.
  • Developer are always clear with detailed context for application failures.
  • Log4j has one of the distinctive features – the notion of inheritance. Using this logger hierarchy feature we are able to control the log statements output at arbitrarily fine granularity but also at great ease. This helps to reduce the volume of logged output and the cost of logging.
  • We can set many targets for the log output such as a file, an OutputStream, a java.io.Writer, a remote log4j server, a remote Unix Syslog daemon, or many other output targets.

Logging Levels

FATAL: shows messages at a FATAL level only.
ERROR: Shows messages classified as ERROR and FATAL levels.
WARNING: Shows messages classified as WARNING, ERROR, and FATAL levels.
INFO: Shows messages classified as INFO, WARNING, ERROR, and FATAL levels.
DEBUG: Shows messages classified as DEBUG, INFO, WARNING, ERROR, and FATAL levels.
ALL – The ALL Level has the lowest possible rank and is intended to turn on all logging.
OFF – The OFF Level has the highest possible rank and is intended to turn off logging.

For more information please go through Apache Log4j.

Example

Log4j Configuration

I am giving here simple logging example using log4j.xml configuration. This will log the messages to the console as well as to file.

I have used here RollingFileAppender so that we can have multiple backup files. You can set maximum number of log files using property MaxBackupIndex. You can specify maximum size of each file using MaxFileSize.

I have used ConsoleAppender for showing output into the console.

You can format log pattern output using PatternLayout class.

You can specify root log level for all loggers or you can also specify individually.

This log4j.xml file is put into the classpath i.e. src directory.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
    <appender name="CA" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
        </layout>
    </appender>
    <appender name="RFA" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="sample.log" />
        <param name="ImmediateFlush" value="true" />
        <param name="MaxFileSize" value="5KB" />
        <param name="MaxBackupIndex" value="5" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="CA" />
        <appender-ref ref="RFA" />
    </root>
</log4j:configuration>

Writing Java Class

Write a simple java class for testing it. We need log4j.jar file to be put into the classpath.

package in.sblog.log4j.test;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
public class TestLog {
    private static Logger logger = Logger.getLogger(TestLog.class);
    public static void main(String[] args) {
        DOMConfigurator.configure("src/log4j.xml");
        logger.debug("log4j configuration is successful.");
    }
}

Output

Console

0    [main] DEBUG in.sblog.log4j.test.TestLog  - log4j configuration is successful.

File

0    [main] DEBUG in.sblog.log4j.test.TestLog  - log4j configuration is successful.

The log file is created under project root directory and the name of the log file is sample.log.

That’s all. Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *