SLF4j Vs Log4j – 那个更好?

本文翻译自SLF4j Vs Log4j – Which one is better?

I have been asked this question multiple times, so I thought to write down my answer as this post in blog itself so others can refer to it from time to time, when needed.

我被问到这个问题很多次了,所以我把问题的答案写在了这篇博客上,以便其他人可以在任何有需要的时候查看。

Simple Logging Facade for Java (SLF4J) is an API designed to give generic access to many logging frameworks; log4j being one of them. Which one you use, is then decided at deployment time, not when you write your code. Best practice is to use slf4j to for your own log statements, and then choose the appropriate backend for it (including log4j as well by configuring to use log4j as a logging backend).

SLF4J 是一套API,它被设计用来以一种通用的方式使用多种logging framework,log4j就是其中的一种。(译者注:其他的logging framework还包括log4j2, java.util.logging, logback,著名的Facade设计模式)。具体使用的是哪一种,是在部署时决定的,而不是在敲代码的时候决定的。Best practice 是用slf4j来记录log,然后为它选择合适的backend(如果你选择log4j,就将log4j配置为logging backend)。

For example, below code you may write in your application class files:

比如,你可能会在你的application class 文件里面写下这样的code:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld
{
  public static void main(String[] args)
  {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }
}

Now all you have to choose, which logging framework you need to use in runtime. For that, you will have to include two jar files:

  1. SLF4j binding jar file
  2. Desired logging framework jar files

现在,你所需要做的是选择在运行时使用哪个logging framework。为此,你会include两个jar文件:

  1. SLF4j binding jar file
  2. Desired logging framework jar files

e.g. to use log4j in your project, you will have to include below given jar files:

  • slf4j-log4j12-1.7.12.jar
  • log4j-1.2.17.jar

例如,为了在你的project使用log4j,你得include以下两个jar文件:

  • slf4j-log4j12-1.7.12.jar
  • log4j-1.2.17.jar

Once you have places both jar files in your application classpath, SLF4j will automatically detect it and start using log4j for processing the log statements based on configuration you provided in log4j configuration file.

在你把这两个jar文件都放到你的application classpath之后,SLF4j会自动的探测到,然后就能根据你在log4j的配置文件中的配置,开始使用log4j处理log语句。

In future, if you want to replace log4j with any other logging framework – All you have to do is replace the binding and logging jar files (along with configuration file). It’s easy. No need to change the actual source code files.

在将来的某个时刻,如果你想将log4j替换成其他的logging framework,你仅仅需要将绑定和logging jar文件(和配置文件一起)替换。非常简单,而没有必要去改变真是的源文件。

So essentially, SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your application and make it easy to replace it in future with more capable library.

所以,本质上说,SLF4J并没有替换log4j,他们是一起工作。他去除了application对log4j的依赖,从而使得在将来可以很容易的将他替换为功能更加强大的类库

I hope that above discussion will help some of us in future.

Happy Learning !!

【1】将SLF4J、Logback、Log4J的关系和行为一起整理出来

你可能感兴趣的:(SLF4j Vs Log4j – 那个更好?)