Why does log4j. XML use slf4j instead of log4j?

Source: Internet
Author: User
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">        <layout class="org.apache.log4j.PatternLayout">            <param name="ConversionPattern" value="%d{yy-MM-dd HH:mm:ss,SSS} %-5p %c(%F:%L) ## %m%n" />        </layout>    </appender>    <logger name="org.apache" additivity="false">        <level value="warn" />        <appender-ref ref="stdout" />    </logger>    <logger name="net.sf.ehcache" additivity="false">        <level value="warn" />        <appender-ref ref="stdout" />    </logger>    <root>        <level value="debug" />        <appender-ref ref="stdout" />    </root></log4j:configuration>

 

 

 

Every Java programmer knows that logs are crucial to any Java application, especially the server. Many programmers are familiar with different logstores such as Java. util. logging, Apache log4j, and logback. But if you do not knowSlf4j(Simple logging facade for Java), it is time to learn to use slf4j in your project.
In this article, we will learn why slf4j is better than log4j or Java. util. logging. It has been a while since I wrote 10 log skills for Java programmers last time. I don't remember everything I wrote about logs.

In any case, let's go back to this topic. slf4j is different from other log class libraries and is quite different from other log class libraries. Slf4j (simple logging facade for Java) is not a real log implementation, but an abstract action layer. It allows you to use any log class library in the background. If you are writing an API or a common class library that can be used internally and externally, you really do not want the client that uses your class library to use the log class library you selected.

If a project has used log4j and you have loaded a class library, for example, Apache active MQ-which depends on another log class library logback, You need to load it as well. However, if Apache active MQ uses slf4j, you can continue to use your log class library without suffering the pain of loading and maintaining a new log framework.

In general, slf4j makes your code independent from any specific log API, which is a good idea for API developers. Although the idea of the abstract log library is no longer a new thing and Apache commons logging is already using this idea, slf4j is now rapidly becoming a log standard in the Java World. Let's take a look at several reasons for using slf4j instead of log4j, logback, or Java. util. logging.

Slf4j compares the advantages of log4j, logback, and Java. util. Logging

As I said before, the main starting point of using slf4j to write log statements in your code is to make your program independent from any specific log class library, depending on a specific class, it may need to be different from your existing configuration, and cause more maintenance troubles. But in addition, the slf4j API feature makes me insist on using slf4j and abandon the lof4j I love for a long time. It is called a placeholder (place holder ), it is represented as "{}" in the code. A placeholder is very similar to % s in the string format () method, because it will be replaced by a provided actual string at runtime. This not only reduces the number of string connections in your code, but also reduces the number of new string objects. Even if you do not need those objects, This is still true, depending on the log level of your production environment, such as string connection at the debug or info level. Because string objects are unchangeable and they are built in a string pool, they consume heap memory and are not needed most of the time, for example, when your application runs at the error level in the production environment, a string is not required to use the debug statement. By using slf4j, you can delay the creation of a string during runtime, which means that only the required String object is created. If you have already used log4j, you are familiar with the alternative solution of using the debug statement in the IF condition, but the placeholder of slf4j is much better than this one.

This is the solution you use in log4j, but it is certainly not interesting and reduces the readability of the code because it adds unnecessary redundant code (boiler-plate code ):

123 if (logger.isDebugEnabled()) {    logger.debug("Processing trade with id: " + id + " symbol: " + symbol);}

On the other hand, if you use slf4j, you can get results in a very concise format, as shown below:

1 logger.debug("Processing trade with id: {} and symbol : {} ", id, symbol);

In slf4j, we do not need to connect strings and do not consume strings that are temporarily not needed. Instead, we write log information in a placeholder and a template format that passes actual values by parameters. What if I have a parameter? Well, you can choose to use the LOG method of the variable parameter version or use it to pass the object array. This is a convenient and efficient log logging method. Remember, before producing the string of the final log information, this method checks whether a specific log level is enabled, this not only reduces memory consumption, but also reduces the CPU time to process string connection commands in advance. Here is the code that uses the slf4j LOG method, from the log4j adapter class log4jloggeradapter in the slf4j-log4j12-1.6.1.jar.

123456 public void debug(String format, Object arg1, Object arg2) {    if (logger.isDebugEnabled()) {        FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);        logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());    }}

At the same time, we also deserve to know that logging has a great impact on the performance of the application. We recommend that you only record the necessary logs in the production process.

How to Use slf4j for log4j Logging

In addition to the above benefits, I want to have a warning, is to use slf4j, you not only need to contain slf4j API jar package, such as slf4j-api-1.6.1.jar, also need the relevant jar package, it depends on the log class library you use in the background. If you want to use slf4j and simple logging facade for Java together with log4j, You need to include the following JAR packages in your classpath, it depends on which slf4j and the log4j version you are using. For example:

  • The slf4j-api-1.6.1.jar-jar for slf4j API
  • The log4j-1.2.16.jar-jar for log4j API
  • Slf4j-log4j12-1.6.1.jar-log4j adapter for slf4j

If you are using Maven to manage your project dependencies, you only need to include the slf4j jar package. MAVEN will contain the dependent packages. To use log4j with slf4j, You can include the following dependencies in POM. xml of your project.

1234567891011 <dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-log4j12</artifactId>    <version>1.6.1</version></dependency> <dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-log4j12</artifactId>    <version>1.6.1</version></dependency>

Also, if you are interested in the log method using the variable parameter version (Variable Argument version), import the slf4j 1.7 version.

Summary

To sum up, I suggest using slf4j instead of using log4j, commons logging, logback, or Java. util. logging.

  1. Using slf4j in your open-source or internal class libraries makes it independent from any specific log implementation. This means that you do not need to manage multiple log configurations or multiple log class libraries, your client is very grateful for this.
  2. Slf4j provides a placeholder-based LOG method, which improves code readability by checking isdebugenabled (), isinfoenabled (), and so on.
  3. By using slf4j's log method, you can delay the overhead of building log information (srting) until you actually need it, which is efficient for memory and CPU.
  4. As a note, fewer temporary strings mean that the garbage collector (Garbage Collector) needs to do better, which means your applications have better throughput and performance.
  5. These benefits are just the tip of the iceberg. You will learn more when you start using sl4j and reading the code. I strongly recommend that any new Java programmer use slf4j for logs instead of other log APIs including log4j.

Read more:

Http://javarevisited.blogspot.com/2013/08/why-use-sl4j-over-log4j-for-logging-in.html#ixzz2konULdTB

 

Relationship between slf4j-api, slf4j-log4j12, and log4j

Log4j can be seen in almost every jar package. In a project composed of multiple sub-projects, conflicts related to slf4j may jump out from time to make you uncomfortable, so what is the relationship between slf4j-api, slf4j-log4j12 and log4j?

Slf4j: simple logging facade for Java, a simple log facade provided for Java. The underlying layer of facade is the interface. It allows users to access different log systems through slf4j in the project as they like. More intuitively, slf4j is a data line. One end is embedded into the program, and the other end is linked to the log system, so that information in the program can be imported to the log system and recorded.

Therefore, the slf4j entry is a collection of many interfaces. It is not responsible for specific log implementation, but is only responsible for finding the appropriate log system for binding during compilation. Which interfaces are defined in the slf4j-api. View the slf4j-api source code can be found, in addition to the public final class loggerfactory class, are interface definition. So slf4j-api is essentially an interface definition.

The relationship between them is clearly described. The example shows the call relationship implemented by the system using log4j as the log framework:

First, the system contains the slf4j-api as the interface for Log Access. Compile when the slf4j-api public final class loggerfactor class private final static void BIND () method will find specific log implementation class binding, mainly through staticloggerbinder. getsingleton () statement call.
② The slf4j-log4j12 is an adapter linking the slf4j-api and the log4j center. It implements the staticloggerbinder interface in the slf4j-apiz, so that the getsingleton () method of the slf4j-log4j12 is bound at compilation.
③ Log4j is a specific log system. Initialize log4j via slf4j-log4j12 to achieve final log output.

Why does log4j. XML use slf4j instead of log4j?

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.