Java Log Series (iii) LOG4J 2

Source: Internet
Author: User
Tags syslog log4j

Log4j1.x has been widely used in various systems and frameworks. Then, 1.x is too old after all, the code has not been updated for a long time. Currently, the log4j 1.x code is difficult to maintain because it relies on many older versions of the JDK API. As a replacement for the log4j 1.x, Slf4j/logback has made great improvements to the log system, so why do we need log4j 2?

1. Log4j 2 is designed as a useful logging framework for security audits. In the Logback framework, when the output log produces an exception, the callee is never told, and Log4j 2, this will be configurable.

2. Log4j 2 uses a new generation of Lmax Disruptor-based unlocked asynchronous log systems. In multithreaded programs, the asynchronous log system throughput is 10 times times higher than log4j 1.x and Logback, while the time delay is lower.

3. LOG4J 2 uses plug-in mechanism, more flexible. Extending the appenders,filters,layouts,lookups and pattern converters will be simpler without having to go higher than any log4j itself.

4. log4j 2 supports custom log levels. You can configure the custom log level in the program or in the configuration file.

5. Log4j 1.x and Logback return a string. This time the problem of encoding is generated. log4j 2 Returns the byte array that is returned.

6. The Syslog Appender of log4j 2 is a socketappender that supports both the BSD Syslog and RFC 5424 formats not only for TCP and UDP.

7. Some of the deadlock problems in log4j1.x have been fixed in logback, however, the logback is still relatively low in concurrent performance. log4j 2 leverages the concurrency mechanism of the JAVA5 and performs very well.

LOG4J 2 supports three types of configuration files: JSON, YAML, and XML. The log4j 2 configuration file loading sequence is:

    1. Log4j2-test.yaml or log4j2-test.yml
    2. Log4j2-test.json or log4j2-test.jsn
    3. Log4j2-test.xml
    4. Log4j2.yaml or log4j2.yml
    5. Log4j2.json or log4j2.jsn
    6. Log4j2.xml

If the configuration file is not found, it will use its default profile, which looks like this:

<?XML version= "1.0" encoding= "UTF-8"?><ConfigurationStatus= "WARN">  <appenders>    <Consolename= "Console"Target= "System_out">      <Patternlayoutpattern= "%d{hh:mm:ss." SSS} [%t]%-5level%logger{36}-%msg%n "/>    </Console>  </appenders>  <Loggers>    <Root Level= "Error">      <Appenderrefref= "Console"/>    </Root>  </Loggers></Configuration>

In other words, it only prints the error level log to the console.

MAVEN configuration:

  <Dependency>            <groupId>org.apache.logging.log4j</groupId>            <Artifactid>Log4j-api</Artifactid>            <version>2.3</version>        </Dependency>        <Dependency>            <groupId>org.apache.logging.log4j</groupId>            <Artifactid>Log4j-core</Artifactid>            <version>2.3</version>        </Dependency>

Test class Bar.java

 Packagecom.lf.testLog4j;ImportOrg.apache.logging.log4j.Logger;ImportOrg.apache.logging.log4j.LogManager;/*** Created by Lufei3 on 2015/7/10.*/ Public classBar {Static FinalLogger Logger = Logmanager.getlogger (Bar.class. GetName ());  Public BooleandoIt () {logger.entry (); Logger.error ("Did it again!"); returnLogger.exit (false); }}

Test class hellolog4j

 Packagecom.lf.testLog4j;ImportOrg.apache.logging.log4j.LogManager;ImportOrg.apache.logging.log4j.Logger;/*** Created by Lufei3 on 2015/7/5.*/ Public classhellolog4j {Private Static FinalLogger Logger = Logmanager.getlogger (hellolog4j.class); /**     * @paramargs*/         Public Static voidMain (string[] args) {Logger.trace ("Entering application."); Bar Bar=NewBar (); if(!Bar.doit ()) {Logger.error ("Didn ' t do it."); } logger.trace ("Exiting application."); }}

The output with the default configuration should be this way

default configuration:logging only errors to the console. 14:38:42.866 [main] Error Com.lf.testlog4j.bar-did it again!14:38:42.867 [main] Error COM.LF.TESTLOG4J.HELLOLOG4J-DIDN ' t do it.

Add config file log4j2.xml, and change log level to trace so the output should be like this

15:04:42.134 [main] TRACE com.lf.testLog4j.HelloLog4j- Entering application. 15:04:42.139 [main] TRACE Com.lf.testLog4j.Bar- entry15:04:42.139 [main] ERROR Com.lf.testlog4j.bar-did it aga in!15:04:42.139 [main] TRACE com.lf.testlog4j.bar-exit with (false)15:04:42.139 [main] ERROR Com.lf.testlog4j.hellolog4j-didn ' t do it.15:04:42.139 [main] TRACE com.lf.testlog4j.hellolog4j-exiting application.

You can control how different Java classes are exported by configuration. For example, I want to set the output level of bar to trace, and the output level of other classes is error, configured as follows:

<Loggers>        <Loggername= "Com.lf.testLog4j.Bar" Level= "Trace"additivity= "false">            <Appenderrefref= "Console"/>        </Logger>        <Root Level= "Error">            <Appenderrefref= "Console"/>        </Root>    </Loggers>

The output is as follows:

15:32:51.510 [main] TRACE Com.lf.testLog4j.Bar- entry15:32:51.512 [main] ERROR Com.lf.testlog4j.bar-did it aga in!15:32:51.512 [main] TRACE com.lf.testlog4j.bar-exit with (false)15:32:51.512 [main] ERROR Com.lf.testlog4j.hellolog4j-didn ' t do it.

References: log4j official documentation

Java Log Series (iii) LOG4J 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.