Introducing Logging With Log4J

Log4j is an open-source logging framework. It enables developers to control logging statements at various granularity levels. It is fully configurable and can be configured using external configuration files.

Components of Log4j Framework

Log4j consists of 3 primary components:

  • Logger: It is responsible for capturing logging information.
  • Appender: It is responsible for publishing logging information captured by the loggers to different destination. Example: console, file etc.
  • Layout: It is responsible for formatting the logging information.

Apart from the primary objects, log4j consists of various auxiliary objects that communicate with the primary objects to perform important tasks in the framework. The important auxiliary objects are:

  • Level: The level object defines the granularity of the logging information. The different logging levels defined by log4j are: ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF.
  • Filter: Filters are used by Appenders to analyze the logging information and make further decisions on whether the logging information should be printed or not. 
  • LogManager: It is responsible for managing the entire logging framework.

Log4j Configuration

Before using log4j in an application, it should be configured using an xml or properties file. This configuration file should be named as log4j.xml or log4j.properties and placed in the application class path. Shown below is a basic log4j configuration file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
	    <param name="conversionPattern" value="%m%n"/>
	</layout>
    </appender>
    
<logger name="com.cubearticle.examples" additivity="false"> <level value="debug"/> <appender-ref ref="console"/> </logger>
<root> <level value="debug" /> <appender-ref ref="console"/> </root> </log4j:configuration>

The configuration file shown above defines an appender, a logger and the root logger.

The appender is defined is a console appender i.e. it would be used to publish logging information to the console. The appender is also provided with a layout which will be used to format the output.

A logger named 'com.cubearticle.examples' is defined, which captures logging information from 'com.cubearticle.examples' package. The root logger is used to capture all the logging information generated in the application. Each logger requires one or more appender object to publish the logging information to its destination. Both the loggers defined above are provided with the console appender.

Dependency:

Log4J requires log4j.jar, we should download and include it in the application class path.


Capture Logging Information

The java class below shows how to capture logging information:

package com.cubearticle.examples;
import org.apache.log4j.Logger; public class TestLogging { public static Logger logger = Logger.getLogger(TestLogging.class); public static void main(String args[]){ if(logger.isDebugEnabled()){ logger.debug("Logging Debug Messages"); } if(logger.isInfoEnabled()){ logger.info("Logging Info Messages"); }
logger.warn("Logging Warn messages"); logger.error("Logging Error messages"); } }

To capture the logging information we first need to create a Logger object by calling the getLogger() method of the Logger class. In our example above we had tried to log messages at different priority levels. In our case all the log messages in the class would get printed to console since we had set the priority level of our logger named "com.cubearticle.examples" to debug. Below is the different priority levels available listed with increasing priority:

ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF

Since we had set the priority of our logger to debug, all the log message with higher priority will also get printed.

NOTE:

Notice that the logger in the configuration file has an attribute 'additivity=false', setting this attribute to false prevents the root logger from printing the log messages again and thus avoid duplicate log messages.

By default all the logging messages are also passes on to the parent loggers (root logger is the parent logger of all loggers). Setting additivity to false prevents this behavior.

RELATED ARTICLES

Logging Different Priority Level Messages to Separate Files

Log4j can be configured to publish different priority level messages in separate files; developers can log error messages in a separate file thus reducing the effort of searching errors in large files

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Using Slf4J Facade with Log4j

Slf4j is a high level logging framework. Its serves as a facade and the actual logging is performed by the underlying logging framework which can be determined at runtime.

View Article