The relationship and debugging of log4j+logback+slf4j+commons-logging

Source: Internet
Author: User
Tags format definition jboss

Background
As the open source framework is becoming richer, many of the log components used by open source frameworks are different. exist in a project, different versions, different frameworks coexist. Causes the log output to be unusually chaotic. Although it does not cause fatal damage to the system, it is clear that the architecture is not sophisticated enough and the pursuit of the ultimate is slightly inadequate.
There are some standard common interface, standard implementation, the existence of various bridges, let me set up the relationship between these frameworks.
From there, we can see 4 parts.
Interface: All log implementations are fitted together and invoked with a unified interface.
Implementation: The current mainstream log implementation
Old log to SLF4J adapter: If the use of slf4j, but only want to use an implementation, want to log4j log system from Logback output, this is very useful.
SLF4J to implemented adapters: These packages are required if you want to develop a specific implementation of SLF4J.

SLF4J relationship to the old log frame
slf4j equals commons-logging, is a common entry for various log implementations, depending on which jar exists in the classpath to determine the specific log implementation library.
Logback-classic (default Logback implementation)
Slf4j-jcl.jar (Apache Commons logging)
Slf4j-logj12.jar (log4j 1.2.4)
Slf4j-jdk14 (java.util.logging)
go to SLFJ for all log calls to a third-party class library or old code that uses the legacy log API
Jcl-over-slf4j.jar/jcl104-over-slf4j:apache Commons Logging 1.1.1/1.0.4, can be replaced directly.
LOG4J-OVER-SLF4J.JAR:LOG4J, the direct replacement can be.
JUL-TO-SLF4J:JDK logging, you need to call Slf4jbridgehandler.install () at the beginning of the program to register the Listener reference Juloverslf4jprocessor, The bean can be defined in Applicationcontext.xml for initialization. Note that the original log4j.properites will expire, and the Logback website provides converters that support conversion from log4j.properties to Logback.xml.

Advantages: Reasons for moving to Logback
SLF4J supports parameterized Logger.error ("account id:{} does not exist", userId), and Farewell to the IF (logger.isdebugenable ()) era.
In addition, the overall performance of logback than log4j is also better, hibernate and other projects have adopted the SLF4J: "Some key operations, such as determining whether to record the operation of a log statement, its performance has been significantly improved. This operation requires 3 nanoseconds in Logback and 30 nanoseconds in log4j. The logback creates a logger (logger) faster: 13 milliseconds, while in log4j it takes 23 milliseconds. What's more, it takes only 94 nanoseconds to get the existing logger, and the log4j takes 2234 nanoseconds and the time is reduced to 1/23. "

Use of slf4j and Logback
1. If the log has more than 3 parameters, you need to write a
Object[] params = {newval, below, above}; Logger.debug ("Value {} was inserted between {} and {}.", params);
Code comparison for commons-logging and slf4j: Commons-logging Sample code:

Import Org.apache.commons.logging.Log;   Import org.apache.commons.logging.LogFactory;      Public class Testlog {     = Logfactory.getlog (testlog.  Class);        Public void print () {         if  (log.isdebugenabled ()) {             log.debug (SQL);              Log.debug (' My name is ' + name + ', I am ' + age + ' years old '. );          }      }  

Example code for SLF4J:

 import   Org.slf4j.Logger;     import   org.slf4j.LoggerFactory;  public  class   testlogbyslf4j {Logger Logger  = Loggerfactory.getlogger (Testlogbyslf4j.      Class  );  public  void   print () {logger.debug (SQL); Logger.debug ( "My name is {}, I am {} years old.")      , name, age); }  }  

2. Because the interior has been optimized, the author argues that SLF4J's logger does not need to be defined as static.
3. Can set the cache post-batch write log file (but if the server restarts, you may lose records that are not written to disk)
4.MDC, using filter, places business information such as the current user name into the MDC, which can be used in the log format definition.
5.JMS Appender for alarms, DB appender for business logs, etc.

Production environment and elegant solutions
The project of our factory is very confusing due to the use of many open source architectures, which makes the log system in the project. There are frequent cases of log packet collisions. For example: commons-logging-1.0.4,commons-logging-1.1.3,log4j,logback,jboss-logging,java.util.logging ... Different versions, different implementations. I have to configure at least log4j,logback,commons-logging three configuration files before I can finish the output of the log. After studying the log system, my factory's maven Pom.xml is as follows

   <!--Log -  <Dependency>      <groupId>Org.slf4j</groupId>      <Artifactid>Slf4j-api</Artifactid>      <version>${org.slf4j-version}</version>  </Dependency>  <Dependency>     <groupId>Org.slf4j</groupId>     <Artifactid>Jcl-over-slf4j</Artifactid>      <version>${org.slf4j-version}</version>  </Dependency>  <Dependency>      <groupId>Org.slf4j</groupId>      <Artifactid>Log4j-over-slf4j</Artifactid>      <version>${org.slf4j-version}</version>  </Dependency>  <Dependency>      <groupId>Org.slf4j</groupId>      <Artifactid>Jul-to-slf4j</Artifactid>      <version>${org.slf4j-version}</version>  </Dependency>  <Dependency>      <groupId>Org.jboss.logging</groupId>      <Artifactid>Jboss-logging</Artifactid>      <version>3.1.4.GA</version>  </Dependency>  <!--<dependency> <groupId>commons-logging</groupId> <artifactid>commons-logging</a rtifactid> <version>1.1.3</version> </dependency> <dependency> <groupid>log4j </groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependen Cy> -  

Added a few important implementation adapters, LOG4J-OVER-SLF4J,LOG4J-OVER-SLF4J,JUL-TO-SLF4J. Then the jboss-logging section is also a unified version control. Delete and exclude all versions of log4j,commons-logging at the same time. Adapters and specific log implementations cannot coexist, otherwise the adapter does not take effect. In this case, we only have the Logback configuration file, because log4j's output has been delegated to slf4j (via LOG4J-OVER-SLF4J), and SLF4J's default implementation is Logback.
where Jul needs to execute an extra line of initialization code

Slf4jbridgehandler.install (); // Jul to slf4j  

Common error debugging
"Error 1" is just a typical error, mainly the second line of the error red Section Log4j:warn No appenders could be found for logger (COM.MCHANGE.V2.LOG.MLOG). Log4j:warn Initialize the log4j system properly. Log4j:warn See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. |
This error occurs because no log4j configuration file is causing it.
Add the Log4j.xml under Classpath and do some configuration.
When the configuration is complete, start the output
2014-02-25 09:30:31:743[info][com.mchange.v2.log.mlog.<clinit> (mlog.java:80)]-MLog clients using log4j Logging.
2014-02-25 09:30:31:780[info][com.mchange.v2.c3p0.c3p0registry.banner (c3p0registry.java:204)]-Initializing c3p0-0.9.1.2 [built 21-may-2007 15:04:56; debug true; Trace:10]
This means that the response is normal.
For example my configuration file is as follows Log4j.xml

<?XML version= "1.0" encoding= "UTF-8"?>  <!DOCTYPE log4j:configuration SYSTEM "Log4j.dtd">  <log4j:configurationxmlns:log4j= ' http://jakarta.apache.org/log4j/'>     <Appendername= "Console"class= "Org.apache.log4j.ConsoleAppender">         <Layoutclass= "Org.apache.log4j.PatternLayout">             <paramname= "Conversionpattern"value= "%d{yyyy-mm-dd hh:mm:ss:sss}[%-5p][%l]-%m%n" />         </Layout>     </Appender>     <Loggername= "Org.springframework"additivity= "false">          < Levelvalue= "Info" />          <Appender-refref= "Console" />      </Logger>      <Root>          < Levelvalue= "Info" />          <Appender-refref= "Console" />      </Root>  </log4j:configuration>  

Reference article log4j.xml detailed configuration http://zhangxiang390.iteye.com/blog/258455

Http://www.cnblogs.com/zhuawang/p/3999235.html

log4j+logback+slf4j+commons-logging Relationship and Commissioning (RPM)

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.