Log4j

Log4j Property Configuration Example

Log4J is an open source project which allows developers output log statements with configured granularity. The configuration can be maintained by the configuration files (XML, Property). Log4J has three main components: Loggers, Appenders and Layouts. These three components work together to help developers configure Log4J to output desired statements in given format and target. The benefit of log statements over simple System.out.print is that it allows you to define which statements gets output, and prevent some from not logging.

1. Loggers

Loggers follow the hierarchical naming rule which states that:

A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger

The root logger resides at the top of the hierarchy and invoking the static Logger.getRootLogger method retrieves it. All other loggers are retrieve by their name: for e.g: if the logger name is MySampleLogger, it can be retrieve by calling Logger.getLogger(MySampleLogger.class);

2. Appender

Log4j allows logging requests to print to multiple destinations. An output destination is called an appender. Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.

  • layout: Appender uses the Layout objects and the conversion pattern associated with them to format the logging information.
  • target – The target may be a console, a file, or another item depending on the appender.
  • level – The level is required to control how to filter of the log messages.
  • threshold – Appender can have a threshold level associated with it independent of the logger level. The Appender ignores any logging messages that have a level lower than the threshold level.
  • filter – The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled by a particular Appender or ignored.

The output of a log statement of logger A will go to all the appenders in A and its ancestors. This is the meaning of the term “appender additivity“. However, if an ancestor of logger A, say B, has the additivity flag set to false, then A‘s output will be directed to all the appenders in A and its ancestors upto and including B but not the appenders in any of the ancestors of B. Loggers have their additivity flag set to true by default.

3. Project Structure

The below image shows the project structure.

Figure 1. Project Structure

4. Java Class

Below is the class which will use Log4J to print log statements.

HelloLog4JProperty.java

import org.apache.log4j.Logger;
/**
 * Class demonstrating Log4J property file configuration.
 */
public class HelloLog4JProperty {

    private static final Logger LOGGER = Logger.getLogger(HelloLog4JProperty.class);

    public static void main(String args[]) {
        LOGGER.info("Log4J property file testing...");
    }
}

5. Property file

The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH. Below is the property file used for configuring Log4J:

log4j.properties

#Set root logger level to INFO and its only appender to TestAppender.
log4j.rootLogger=INFO, TestAppender

# TestAppender is set to be a ConsoleAppender.
log4j.appender.TestAppender=org.apache.log4j.ConsoleAppender

# TestAppender uses PatternLayout.
log4j.appender.TestAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.TestAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

6. Debug Levels

Below is the description of the log levels used in log4j.

ALL – All levels including custom levels.
DEBUG – Designates fine-grained informational events that are most useful to debug an application.
ERROR – Designates error events that might still allow the application to continue running.
FATAL – Designates very severe error events that will presumably lead the application to abort.
INFO – Designates informational messages that highlight the progress of the application at coarse-grained level.
OFF – The highest possible rank and is intended to turn off logging.
TRACE – Designates finer-grained informational events than the DEBUG.
WARN – Designates potentially harmful situations.

A log request of level L1 in a logger with level L2, is enabled if L1 >= L2. This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.

7. Maven Pom file

Below is the pom.xml which defines the dependency

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.javacodegeeks</groupId>
    <artifactId>log4j-property</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <dependencies>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>
</project>

8. Output

Below is the result of running the HelloLog4JProperty class

0 [main] INFO HelloLog4JProperty - Log4J property file testing...

Process finished with exit code

9. Download the source file

This was an example of Log4J configuration using property file in java.

Download
You can download the full source code of this example here: Log4JProperty.zip

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button