使用 SLF4J 发送/重定向/路由 java.util.logging.Logger (JUL) 到 Logback?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6020545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:00:14  来源:igfitidea点击:

Send/redirect/route java.util.logging.Logger (JUL) to Logback using SLF4J?

javaloggingslf4j

提问by Zombies

Is it possible to have a typical call to java.util.logging.Loggerand have it route to Logback using SLF4J? This would be nice since I wouldn't have to refactor the old jul code line by line.

是否可以java.util.logging.Logger使用 SLF4J 对 Logback 进行典型调用并将其路由到 Logback?这会很好,因为我不必逐行重构旧的 jul 代码。

EG, say we have this line:

EG,假设我们有这条线:

private static Logger logger = Logger.getLogger(MahClass.class.getName());
//...
logger.info("blah blah blah");

It would be nice to configure this to call through SLF4J.

将此配置为通过 SLF4J 调用会很好。

回答by Dejan Milosevic

It's very easy and not a performance issue anymore.

这很容易,不再是性能问题。

There are two ways documented in the SLF4J manual. There are also precise examples in the Javadocs

SLF4J 手册中记录了两种方法。Javadocs中也有精确的例子

Add jul-to-slf4j.jar to your classpath. Or through maven dependency:

将 jul-to-slf4j.jar 添加到您的类路径中。或者通过 Maven 依赖:

<dependency>
    <groupId>org.slf4j</groupId>
     <artifactId>jul-to-slf4j</artifactId>
    <version>1.7.0</version>
</dependency>

If you don't have logging.properties (for java.util.logging), add this to your bootstrap code:

如果您没有 logging.properties(用于 java.util.logging),请将其添加到您的引导程序代码中:

SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();

If you have logging.properties (and want to keep it), add this to it:

如果您有 logging.properties(并想保留它),请将其添加到其中:

handlers = org.slf4j.bridge.SLF4JBridgeHandler

In order to avoid performance penalty, add this contextListener to logback.xml (as of logback version 0.9.25):

为了避免性能损失,将此 contextListener 添加到 logback.xml(从 logback 版本 0.9.25 开始):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <!-- reset all previous level configurations of all j.u.l. loggers -->
        <resetJUL>true</resetJUL>
    </contextListener> 

    ...

</configuration>