Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

log consolidation with log4j2

DZone's Guide to

log consolidation with log4j2

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

log4j, slf4j, logback, commons-logging... I keep wondering which logging strategy I should use.

Recently, I consolidated the logging library for my project to log4j2 . Yes, it's a new version of log4j!

1. My (your) project policy

  • Develop new java/web project.
  • Use log4j2.x logger for new code.
  • The other log that is output through slf4j commons-logging should be also consolidated to log4j2.
  • One configuration file. log4j2.xml
  • Use maven as a build tool.

2. pom.xml

<dependencies>
    <dependency>
        <groupid>org.apache.logging.log4j</groupid>
        <artifactid>log4j-core</artifactid>
        <version>2.0-beta8</version>
    </dependency>
    <dependency>
        <groupid>org.apache.logging.log4j</groupid>
        <artifactid>log4j-jcl</artifactid>
        <version>2.0-beta8</version>
    </dependency>
    <dependency>
        <groupid>org.apache.logging.log4j</groupid>
        <artifactid>log4j-slf4j-impl</artifactid>
        <version>2.0-beta8</version>
    </dependency>
 
    ... other dependency...
</dependencies>

3. src/main/resources/log4j.xml

<configuration>
    <appenders>
        <Console name="console">
            <PatternLayout pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} %-5level %logger{32} %msg%n" />
        </Console>
    </appenders>
    <loggers>
        <logger name="org.springframework"
              level="debug" additivity="false">
            <appender-ref ref="console" />
        </logger>
        <logger name="com.example.myapp"
              level="debug" additivity="false">
            <appender-ref ref="console" />
        </logger>
        <root level="info">
            <appender-ref ref="console" />
        </root>
    </loggers>
</configuration>

4. Write code

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
public class Foo {
    private static Logger logger = LogManager.getLogger();
    public void bar(String a, String b) {
        logger.debug("a={},b={}", a, b);
    }
}

The point of the sample code is place holder, that is new functionality of log4j2.x .

If you wrote the code like 'logger.debug("a=" + a + ",b=" + b); ' , The logging performance will be down. See log4j2 performance for detail.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}