SLF4j异常信息

在使用SLF4j时出现如下异常:

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的Logger对象。代码如下:

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

public class LoggerDemo extends BaseDemo {

	private static Logger logger = LoggerFactory.getLogger(LoggerDemo.class);

	public static void main(String[] args) {
		logger.info("日志");
	}
}

那是什么原因导致slf4j抛出此异常呢?正常执行以上代码会发现程序能够正常执行,但日志没有答应。

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”原因及解决方案

导致此异常的原因是:在运行时,没有日志的实现(或者说日志的绑定),所以slf4j默认使用了一个空实现。

因此也就是缺少了相关的jar包,因为slf4j-api包中只有方法定义,没有具体的方法实现,所以需要引入具体的实现包。

解决方案

官网解决方案如下:

This error is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

可以引入slf4j的实现包,如slf4j-log4j12.jar,引入后再启动项目就可以看到不在报错了。另外使用log4j2的话,可以引入log4j-slf4j-impl-2.10.0.jar包,这是log4j对slf4j相关方法的实现。

针对pom.xml文件可以配置如下:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
</dependency>

完整的代码如下:

<dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
       <version>1.7.5</version>
   </dependency>
   <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-log4j12</artifactId>
       <version>1.7.5</version>
   </dependency>

或如下代码:

<dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
       <version>1.7.5</version>
   </dependency>
   <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
       <version>1.6.4</version>
   </dependency>

注意以上代码修改为匹配或最新的版本即可。

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”&SLF4J: Defaulting to no-operation (NOP) logger implementation异常解决方案插图


SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”&SLF4J: Defaulting to no-operation (NOP) logger implementation异常解决方案插图1

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2019/11/03/slf4j-failed-to-load-class/