我们正在为几个 Web 应用程序从 log4j 迁移到 logback。在关闭我们的应用程序时,我们当前调用:
org.apache.log4j.LogManager.shutdown();
应该刷新所有异步日志记录并关闭所有外部资源(文件、套接字)。
logback 中是否有类似的东西,或者它是否会在关机时自动刷新?
麦克风
似乎只是添加<shutdownHook/>
到配置中应该停止上下文。
来自logback 文档:
<configuration>
<!-- in the absence of the class attribute, assume
ch.qos.logback.core.hook.DelayingShutdownHook -->
<shutdownHook/>
....
</configuration>
在指定延迟后停止 Logback 上下文的 ShutdownHook 实现。默认延迟为 0 毫秒(零)。
这是一个简单的方法:
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
...
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
// Check for logback implementation of slf4j
if (loggerFactory instanceof LoggerContext) {
LoggerContext context = (LoggerContext) loggerFactory;
context.stop();
}
我不知道像 log4j 这样的整体管理器关闭,但是当我使用 ServletContextListener 破坏它们的上下文时,我会关闭所有单独的上下文记录器,如下所示:
ContextSelector selector = StaticLoggerBinder.getSingleton().getContextSelector();
LoggerContext context = selector.detachLoggerContext(contextName);
if (context != null) {
Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
context.reset();
} else {
System.err.printf("No context named %s was found", contextName);
}
此外,LoggerContext.stop() 是可用的,并且在内部执行一些相同的功能,但我不使用它,所以我无法评论它是否比重置更好。
从 1.1.10 版本开始,logback 负责在 web 应用停止或重新加载时停止当前的 logback-classic 上下文。
这是更新的文档:https ://logback.qos.ch/manual/configuration.html#webShutdownHook