如何简单地将slf4j添加到pom.xml包装log4j?

cod*_*ing 21 spring log4j slf4j

从我在示例中看到的春天pom.xml文件是他们为slf4j和log4j添加了一些条目,并且当你在spring应用程序中使用log4j时,它将被slf4j库包装.

有人可以向我解释这是如何神奇地发生的吗?

小智 29

Spring仍然commons-logging 用于所有内部日志记录(向后兼容性).如果您希望使用其他一些日志框架(log4j),那么您需要将调用接到commons logging您选择的框架.否则,您将必须维护多个日志记录配置.

slf4j作为各种日志框架简单的门面(jul,log4j,jcl,logback),并允许您在部署时所需的日志框架插头.

您可以提供slf4j's桥接实现,而不是使用第三方框架强加的日志框架实现,它实际上只是转发日志记录调用slf4j或其具体绑定.

Maven pom.xml的日志记录部分通常如下所示:

<!-- remove the real commons-logging from classpath -->
<!-- declare as provided or exclude from spring jars -->
<dependency>
    <artifactId>commons-logging</artifactId>
    <groupId>commons-logging</groupId>
    <version>1.0</version>
    <scope>provided</scope>
</dependency>

<!-- add slf4j interfaces to classpath -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.4</version>
    <scope>compile</scope>
</dependency>

<!-- add commons logging to slf4j bridge to classpath --> 
<!-- acts as jcl but routes commons-logging calls to slf4j -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.6.4</version>
    <scope>runtime</scope>
</dependency>

<!-- add log4j binding to classpath -->
<!-- routes slf4j calls to log4j -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.4</version>
    <scope>runtime</scope>
</dependency>

<!-- add log4j to classpath -->
<!-- does the logging -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这与Spring容器无关,也没有依赖注入,它是纯类路径,类加载器的东西......

请参阅 下面进一步的细节链接.


kan*_*kan 5

slf4j是一个日志记录API,它什么也不做,只是一堆接口。log4j是一个具有具体类的日志系统。有一个slf4j-log4j库使用log4j作为slf4j API的后端。

一些项目明确依赖于log4j,它们称为具体类。因此,您不能将仅使用slf4j API明智地用于项目的其他后端(例如,logback或jul或apache commons或其他)使用。

一个技巧可以用模拟实现(桥)代替log4j类,该实现只是将所有调用重定向到sl4j。在maven中,您只需声明一个具有很高版本号的依赖项,并且此模拟程序被视为超现代log4j库。