[英]How to force log4j to be used but not slf4j
编辑:为了澄清这个问题,我添加了许多解释。
在我的项目依赖项中,我同时拥有slf4j
和log4j
。 由于某些技术原因,这无法更改。
>gradlew dependencies
Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could
not be reused, use --status for details
> Task :dependencies
.
.
| | | +--- org.springframework.boot:spring-boot-starter-logging:2.5.7
| | | | +--- ch.qos.logback:logback-classic:1.2.7
| | | | | +--- ch.qos.logback:logback-core:1.2.7
| | | | | \--- org.slf4j:slf4j-api:1.7.32
| | | | +--- org.apache.logging.log4j:log4j-to-slf4j:2.14.1
| | | | | +--- org.slf4j:slf4j-api:1.7.25 -> 1.7.32
| | | | | \--- org.apache.logging.log4j:log4j-api:2.14.1 -> 2.17.0
| | | | \--- org.slf4j:jul-to-slf4j:1.7.32
| | | | \--- org.slf4j:slf4j-api:1.7.32
.
.
+--- org.apache.logging.log4j:log4j-core:2.17.0
| \--- org.apache.logging.log4j:log4j-api:2.17.0
+--- org.apache.logging.log4j:log4j-api:2.17.0
BUILD SUCCESSFUL in 16s
1 actionable task: 1 executed
我想在代码中设置日志级别,以及只能使用log4j
完成的 AFAIK。 结果,我只是寻找一种方法来制作此代码行( LogManager
是log4j
的一部分)返回log4j
实现而不是slf4j
实现:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
.
.
private final Logger logger = LogManager.getLogger(getClass());
可悲的是,记录器的 class 返回是org.apache.logging.slf4j.SLF4JLogger
:
System.out.println("logger class is: [" + logger.getClass() + "]");
output:
logger class is: [class org.apache.logging.slf4j.SLF4JLogger]
尽管听起来很简单,但我无法做到这一点,也无法在网上找到示例。 可以做什么?
LogManager 的完整 class 路径是什么? 它必须被导入,在那里你应该看到完整的 class。
我的猜测是您需要更改 Import 以导入一些 log4j LogManager,而不是 slf4j。
Log4j 2.x Core and the Log4j to SLF4J Adapter are two implementations of the Log4j 2.x API. 如果它们都存在于类路径中,则使用log4j-to-slf4j
。 这就是您的情况:使用 Log4j 2.x API 记录的消息被发送到 SLF4J,后者将它们发送到 Logback。
也就是spring-boot-starter-logging
带来的标准日志配置。 如果您想使用 Log4j 2 作为后端,则需要排除该工件并添加spring-boot-starter-log4j2
。
无论如何,由于您使用的是 Spring 引导,因此您有两种方法可以设置记录器的级别:
使用 Spring Boot 的LoggingSystem
抽象(适用于所有可用的日志系统):
final LoggingSystem loggingSystem = LoggingSystem.get(getClass().getClassLoader()); loggingSystem.setLogLevel("loggerName", LogLevel.DEBUG);
使用底层日志系统。 在您的情况下,它是 Logback,因此您应该使用:
final Logger logger = LoggerFactory.getLogger("loggerName"); if (logger instanceof ch.qos.logback.classic.Logger) { ((ch.qos.logback.classic.Logger) logger).setLevel(Level.DEBUG); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.