log4j2 xml configuration example

log4j2 example

Here are some sample log4j2 xml configurations.

These configurations should be included in a file named log4j2.xml and placed on the classpath.

Download source code > log4j2 xml configuration source code (4883)

Console Appender

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info" additivity="false">
            <AppenderRef ref="console"/>
        </Root>
    </Loggers>
</Configuration>

Console appender prints all logs to console. Here is a sample output using above configuration.

[INFO ] 2014-07-23 22:04:31.447 [main] LogDemo - Hello world - info log

Daily Rolling File Appender

Daily rolling file appender prints logs to a file. Difference between file appender and daily rolling file appender is, daily rolling file appender creates a log file per day.

This configuration is widely used in commercial systems due to following  benefits,

  • Size of a single log file is smaller
  • Log analysis is easy
  • Old log files can be archived or deleted

Here is a sample log4j2 configuration for a daily rolling appender.


<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
<Properties>
<Property name="log-path">logs</Property>
</Properties>

<Appenders>
<RollingFile name="file-log" fileName="${log-path}/mycuteblog-info.log"
filePattern="${log-path}/mycuteblog-info-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
</RollingFile>

<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.mycuteblog" level="info" additivity="false">
<appender-ref ref="file-log" level="info"/>
</Logger>
<Root level="info" additivity="false">
<appender-ref ref="console"/>
</Root>
</Loggers>
</Configuration>

Separate log for error logs

Using following configuration you can have a separate log file for error logs.


<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="log-path">logs</Property>
    </Properties>
    <Appenders>
        <Console name="console-log" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"/>
        </Console>
        <RollingFile name="trace-log" fileName="${log-path}/mycuteblog-trace.log"
                     filePattern="${log-path}/dating-trace-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
        </RollingFile>
        <RollingFile name="error-log" fileName="${log-path}/dating-error.log"
                     filePattern="${log-path}/mycuteblog-info-error-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.mycuteblog.log4j2" level="debug" additivity="false">
            <appender-ref ref="trace-log" level="info"/>
            <appender-ref ref="error-log" level="error"/>
            <appender-ref ref="console-log" level="info"/>
        </Logger>
        <Root level="info" additivity="false">
            <AppenderRef ref="console-log"/>
        </Root>
    </Loggers>
</Configuration>

log4j2 full example

Here is  a sample java code with all above configurations. I have used maven for dependency management.

LogDemo.java


package com.mycuteblog.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
* Created by sadupa on 7/26/14.
*/
public class LogDemo {

private static final Logger logger = LogManager.getLogger(LogDemo.class.getName());

public static void main(String[] args){

logger.debug("Hello world - debug log");
logger.info("Hello world - info log");
logger.warn("Hello world - warn log");
logger.error("Hello world - error log");
}
}

log4j2.xml


<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="log-path">logs</Property>
</Properties>
<Appenders>
<Console name="console-log" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"/>
</Console>
<RollingFile name="trace-log" fileName="${log-path}/mycuteblog-trace.log"
filePattern="${log-path}/mycuteblog-trace-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
</RollingFile>
<RollingFile name="error-log" fileName="${log-path}/mycuteblog-error.log"
filePattern="${log-path}/mycuteblog-error-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.mycuteblog.log4j2" level="debug" additivity="false">
<appender-ref ref="trace-log" level="debug"/>
<appender-ref ref="error-log" level="error"/>
<appender-ref ref="console-log" level="debug"/>
</Logger>
<Root level="info" additivity="false">
<AppenderRef ref="console-log"/>
</Root>
</Loggers>
</Configuration>

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.mycuteblog</groupId>
    <artifactId>log4j2Demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <mainClass>com.mycuteblog.log4j2.LogDemo</mainClass>
                        <classpathPrefix>dependency-jars/</classpathPrefix>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.5.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>
                            ${project.build.directory}/dependency-jars/
                        </outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        </plugins>
    </build>
</project>

Download source code > log4j2 xml configuration source code (4883)

Here is the output of above code.

 [DEBUG] 2014-07-26 10:12:50.139 [main] LogDemo - Hello world - debug log
 [INFO ] 2014-07-26 10:12:50.142 [main] LogDemo - Hello world - info log
 [WARN ] 2014-07-26 10:12:50.142 [main] LogDemo - Hello world - warn log
 [ERROR] 2014-07-26 10:12:50.142 [main] LogDemo - Hello world - error log
 

 

 

Enjoyed this article? Share with friends

  • Thanks for post. Your example configuration helped me.

  • Thanks!

  • Sherif Hanno

    Thanks a lot. Really helpful :)

  • Björn Bochmann

    Thanks for your Tutorial! It helped me a lot to set up the basics. But I have a major problem. I want to write the log file into the appdata directory of my Application. Thats doesnt run.

    The first line in my Main Method is:
    System.setProperty(“user.home”, “APPDATA”);

    In my log4j Properties i want to call it:
    ${user.home}FinanzverwaltungLogs

    But when I start the Application it doesnt write the log.

    If you need to watch more code you can look in my git:
    https://github.com/BND-Games/Finance-Managment/tree/development

    I hope you can help me! :-)

  • karthi keyan

    Thanks for your Tutorial! I have same problem as Björn Bochmann has.

  • Eber Bezzone

    Hi, i’ve a problem, i try o use this and when run i don’t have problem, i see on the console everything, and create the folder with the archive inside, but never wirte the archive.
    I run your aplication and write the archve, so i don’t understan.
    Sorry my english.

    • Jannis Alexakis

      Try changing line 30 of log4j2.xml from to

  • Trav

    Very helpful post — thanks man.

  • Prakruti Pathik

    Very useful post.. Helped me resolve the bug

Subscribe

Subscribe to our email feed and never miss a post

Join Us