SLF4J
Simple Logging Facade for Java (SLF4J), SLF4J是各种日志记录框架(例如java.util.logging,logback,log4j)的抽象,在使用 时需绑定所需的日志框架。
需引入以下依赖,仅包含slf4j-api-1.7.30.jar
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
Hello World
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");
}
}
如果不想写 Logger logger = LoggerFactory.getLogger(HelloWorld.class); 这句,可以在类上增加@SLF4j注解,然后log.**
引入slf4j-api-1.7.30.jar后执行上面的将报错
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
与日志框架绑定
选择下面其中一个绑定。
slf4j-log4j12-1.7.28.jar
Binding for log4j version 1.2, a widely used logging framework. You also need to place log4j.jar on your class path.
slf4j-jdk14-1.7.28.jar
Binding for java.util.logging, also referred to as JDK 1.4 logging
slf4j-nop-1.7.28.jar
Binding for NOP, silently discarding all logging.
slf4j-simple-1.7.28.jar
Binding for Simple implementation, which outputs all events to System.err. Only messages of level INFO and higher are printed. This binding may be useful in the context of small applications.
slf4j-jcl-1.7.28.jar
Binding for Jakarta Commons Logging. This binding will delegate all SLF4J logging to JCL.
*logback-classic-1.2.3.jar *
(requires logback-core-1.2.3.jar)*
遇到的错误
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/local/******-1.0.0.jar!/BOOT-INF/lib/logback-classic-1.2.3.jar!/org/s
lf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/******-1.0.0.jar!/BOOT-INF/lib/log4j-slf4j-impl-2.13.3.jar!/org
/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/******-1.0.0.jar!/BOOT-INF/lib/slf4j-log4j12-1.7.30.jar!/org/sl
f4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
解决办法:
1.通过mvn dependency:tree 查看依赖树
2.只用logback的,其他的在pom.xml排除掉