Why use SLF4J instead of Log4J [transfer]

Source: ImportNew - Jaskey

Link: http://www.importnew.com/7450.html

Posted on December 2, 2013

In this article, we will learn why using SLF4J is better than log4j or java.util.logging. It's been a while since the last time I wrote 10 logging tips for Java programmers , and I can't remember everything I wrote about logging.

 

        Anyway, let's get back to the topic, SLF4J is very different from other logging libraries. SLF4J (Simple logging Facade for Java) is not a real logging implementation, but an abstraction layer that allows you to use any logging library in the background. If you're writing an API or generic library that can be used both internally and externally, then you really don't want clients using your library to have to use the logging library of your choice.

 

       If a project already uses log4j, and you load a library, say Apache Active MQ, which depends on another logging library, logback, then you need to load that as well. But if Apache Active MQ uses SLF4J, you can keep using your logging library and suffer the pain of loading and maintaining a new logging framework.

 

       In general, SLF4J makes your code independent of any particular logging API, which is a good idea for API developers. While the idea of ​​an abstract logging library is not new and is already being used by Apache commons logging, SLF4J is now fast becoming the logging standard in the Java world. Let's look at a few more reasons to use SLF4J instead of log4j, logback or java.util.logging.

 

Advantages of SLF4J over Log4J, logback and java.util.Logging

 

       As I said before, the main starting point for using SLF4J to write logging statements in your code is to make your program independent of any specific logging class library, depending on a specific class may require different configuration than you already have, and lead to more Much maintenance hassle. But in addition to that, there is one more feature of the SLF4J API that makes me stick with SLF4J and ditch my long-time favorite Lof4j, which is called a place holder, represented in the code as "{}" characteristics. A placeholder is a %s very similar to String's format() method in that it is replaced at runtime by an actual string provided. This not only reduces the number of string concatenations in your code, but also saves new String objects. Even though you may not need those objects, this still holds, depending on the log level of your production environment, such as string concatenation at DEBUG or INFO level. Because String objects are immutable and they are built in a String pool, they consume heap memory and most of the time they are not needed, for example when your application runs at ERROR level in production, A String used in a DEBUG statement is not required. By using SLF4J, you can delay the creation of strings at runtime, which means that only the required String objects are created. And if you're already using log4j, you're already familiar with the workaround of using debug statements in if conditions, but SLF4J's placeholders are much more useful than this.

 

       This is the scheme you'd use in Log4j, but it's certainly not interesting at all and reduces code readability by adding unnecessary boiler-plate code:

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 compact format, like the one shown below:

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

       In SLF4J, we don't need string concatenation and don't cause temporarily unnecessary string consumption. Instead, we write log messages in a template format that takes placeholders and passes actual values ​​as parameters. You might be thinking what if I have a lot of parameters? Well, then you can choose to use the variadic version of the log method or pass it as an array of Objects. This is a fairly convenient and efficient method of logging. Remember, this method checks to see if a particular log level is turned on before producing the final log message string, which not only reduces memory consumption but also reduces the CPU time to process string concatenation commands in advance. Here is the code that uses the SLF4J logging method, from the Log4j adapter class Log4jLoggerAdapter in slf4j-log4j12-1.6.1.jar.

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, it is also worth knowing that logging has a great impact on the performance of the application. It is recommended that only necessary logging be performed in production.

 

How to use SLF4J for Log4J logging

 

       In addition to the above benefits, I think there is a caveat, that is, in order to use SLF4J, you need not only the API jar package containing SLF4J, such as slf4j-api-1.6.1.jar, but also the related Jar package, which depends on what you use in the background log library. If you want to use SLF4J with Log4J, Simple Logging Facade for Java, you need to include the following Jars in your classpath, depending on which SLF4J and the version of Log4J you are using. E.g:

  • slf4j-api-1.6.1.jar – JAR for SLF4J API
  • 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, and maven will include the relevant packages of its dependencies. In order to use Log4J with SLF4J, you can include the following dependencies in the pom.xml of your project.

<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 logging methods using the variable argument version, then import the SLF4J 1.7 version.

 

Summarize

       To sum up what I said this time, I recommend using SLF4J instead of directly using Log4j, commons logging, logback or java.util.logging is sufficient.

  1. Using SLF4J in your open source or internal library makes it independent of any one specific logging implementation, which means there is no need to manage multiple logging configurations or multiple logging libraries, which your clients will appreciate.
  2. SLF4J provides placeholder-based logging methods, which improve code readability by removing checks for isDebugEnabled(), isInfoEnabled(), etc.
  3. By using SLF4J's logging method, you can defer the overhead of building logging information (Srting) until you really need it, which is both memory and CPU efficient.
  4. As a side note, fewer ephemeral strings means a better job for the Garbage Collector, which means better throughput and performance for your application.
  5. These benefits are just the tip of the iceberg, you will know more as you start using SL4J and read the code in it. I strongly suggest that any new Java programmer should use SLF4J for logging instead of other logging APIs including Log4J.

Read more:

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

Original link: javarevisited

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326678214&siteId=291194637