Log4j Tutorial
  • log4j - Tutorial
  • - Css
  • - W3css
  • log4j - Useful Resources
  • Log4j - Ebook Download

  • Log4j

    Apache Log4j is a Apache Logging Services project of the Apache Software Foundation. Log4j is one of several Java logging frameworks.

    Gülcü has since started the SLF4J and Logback projects, with the intention of offering a successor to Log4j.

    The Apache Log4j team has created a successor to Log4j 1 with version number 2. Log4j 2 was developed with a focus on the problems of Log4j 1.2, 1.3, java.util.logging and Logback, and addresses issues which appeared in those frameworks. In addition, Log4j 2 offers a plugin architecture which makes it more extensible than its predecessor. Log4j 2 is not backwards compatible with 1.x versions, although an "adapter" is available.

    On August 5, 2015 the Apache Logging Services Project Management Committee announced that Log4j 1 had reached end of life and that users of Log4j 1 are recommended to upgrade to Apache Log4j 2.

    Apache Log4j 2

    Apache Log4j 2 is the successor of Log4j 1 which was released as GA version in July 2014. The framework was rewritten from scratch and has been inspired by existing logging solutions, including Log4j 1 and java.util.logging. The main differences from Log4j 1 are:

    One of the most recognized features of Log4j 2 is the performance of the "Asynchronous Loggers". Log4j 2 makes use of the LMAX Disruptor. The library reduces the need for kernel locking and increases the logging performance by a factor of 12. For example, in the same environment Log4j 2 can write more than 18,000,000 messages per second, whereas other frameworks like Logback and Log4j 1 just write < 2,000,000 messages per second.

    Log4j log levels

    The following table defines the built-in log levels and messages in Log4j, in decreasing order of severity. The left column lists the log level designation in Log4j and the right column provides a brief description of each log level.

    Log4j 2 allows users to define their own log levels. A source code generator tool is provided to create Loggers that support custom log levels identically to the built-in log levels. Custom log levels can either complement or replace the built-in log levels.

    Log4j configuration

    Log4j can be configured through a configuration file or through Java code. Configuration files can be written in XML, JSON, YAML, or properties file format. Within a configuration you can define three main components: Loggers, Appenders and Layouts. Configuring logging via a file has the advantage that logging can be turned on or off without modifying the application that uses Log4j. The application can be allowed to run with logging off until there's a problem, for example, and then logging can be turned back on simply by modifying the configuration file.

    Loggers are named log message destinations. They are the names that are known to the Java application. Each logger is independently configurable as to what level of logging FATAL, ERROR, etc. it currently logs. In early versions of Log4j, these were called category and priority, but now they're called logger and level, respectively. A Logger can send log messages to multiple Appenders.

    The actual outputs are done by Appenders. There are numerous Appenders available, with descriptive names, such as FileAppender, RollingFileAppender, ConsoleAppender, SocketAppender, SyslogAppender, and SMTPAppender. Log4j 2 added Appenders that write to Apache Flume, the Java Persistence API, Apache Kafka, NoSQL databases, Memory-mapped files, Random Access files and ZeroMQ endpoints. Multiple Appenders can be attached to any Logger, so it's possible to log the same information to multiple outputs; for example to a file locally and to a socket listener on another computer.

    Appenders use Layouts to format log entries. A popular way to format one-line-at-a-time log files is PatternLayout, which uses a pattern string, much like the C / C++ function printf. There are also HTMLLayout and XMLLayout formatters for use when HTML or XML formats are more convenient, respectively. Log4j 2 added Layouts for CSV, Graylog Extended Log Format GELF, JSON, YAML and RFC-5424.

    In Log4j 2, Filters can be defined on configuration elements to give more fine-grained control over which log entries should be processed by which Loggers and Appenders. In addition to filtering by log level and regular expression matching on the message string, Log4j 2 added burst filters, time filters, filtering by other log event attributes like Markers or Thread Context Map and JSR 223 script filters.

    To debug a misbehaving configuration:

    To find out where a log4j2.xml configuration file was loaded from inspect getClass.getResource"/log4j2.xml".

    There is also an implicit "unconfigured" or "default" configuration of Log4j, that of a Log4j-instrumented Java application which lacks any Log4j configuration. This prints to stdout a warning that the program is unconfigured, and the URL to the Log4j web site where details on the warning and configuration may be found. As well as printing this warning, an unconfigured Log4j application will only print ERROR or FATAL log entries to standard out.

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="trace" monitorInterval="60">
        <Property name="filename">target/test.log</Property>
        <Console name="STDOUT">
          <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>
        <File name="file" fileName="${filename}">
            <pattern>%d %p %c{1.} [%t] %m%n</pattern>
             loggers whose name starts with 'org.springframework' will only log messages of level "info" or higher;
             if you retrieve Loggers by using the class name e.g. Logger.getLoggerAClass.class
             and if AClass is part of the org.springframework package, it will belong to this category
        <Logger name="org.springframework" level="info" additivity="false" />
            Filter example: for loggers whose name starts with 'com.mycompany.myproduct',
            log entries of level "debug" or higher whose ThreadContextMap data contains
            the key-value pair "test=123", also send these log entries to the "STDOUT" appender.
        <Logger name="com.mycompany.myproduct" level="debug" additivity="true">
            <KeyValuePair key="test" value="123"/>
          <AppenderRef ref="STDOUT"/>
            By default, all log messages of level "trace" or higher will be logged.
            Log messages are sent to the "file" appender and 
            log messages of level "error" and higher will be sent to the "STDOUT" appender.
        <Root level="trace">
          <AppenderRef ref="file"/>
          <AppenderRef ref="STDOUT" level="error"/>
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
             an appender is an output destination, such as the console or a file;
             names of appenders are arbitrarily chosen.
        <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern"
                    value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
             loggers of category 'org.springframework' will only log messages of level "info" or higher;
             if you retrieve Loggers by using the class name e.g. Logger.getLoggerAClass.class
             and if AClass is part of the org.springframework package, it will belong to this category
        <logger name="org.springframework">
            <level value="info"/>
             everything of spring was set to "info" but for class 
             PropertyEditorRegistrySupport we want "debug" logging 
        <logger name="org.springframework.beans.PropertyEditorRegistrySupport">
            <level value="debug"/>
        <logger name="org.acegisecurity">
            <level value="info"/>
                all log messages of level "debug" or higher will be logged, unless defined otherwise 
                all log messages will be logged to the appender "stdout", unless defined otherwise 
            <level value="debug" />
            <appender-ref ref="stdout" />


    TTCC is a message format used by log4j. TTCC is an acronym for Time Thread Category Component. It uses the following pattern:

     %r [%t] %-5p %c %x - %m%n


    Example output 467 [main] INFO org.apache.log4j.examples.Sort - Exiting main method.