gpt4 book ai didi

java - 配置 LogBack/ConsoleAppender 以写入 STDERR

转载 作者:行者123 更新时间:2023-12-01 11:37:11 54 4
gpt4 key购买 nike

我想使用 ConsoleAppender 配置 Logback 以使用 stderr,而不是 stdout。特别是,我想使用纯代码而不是properties/xml 文件来完成此操作。这是我的尝试。关于此代码的关键说明:当调用 .reset() 时(按照下面的代码),不会有任何日志输出。当不调用.reset()时,日志全部发送到STDOUT(这表明下面的代码根本不起作用)。

实现这一点的关键是什么?

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import org.slf4j.LoggerFactory;

// stuff

private static Logger buildLogger() {


LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(henson.class);
lc.reset();

PatternLayoutEncoder ple = new PatternLayoutEncoder();

ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();

ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<>();
ca.setTarget("System.err");
ca.setContext(lc);
ca.start();
logger.detachAndStopAllAppenders();
logger.addAppender(ca);
logger.setLevel(Level.DEBUG);

return logger;
}

最佳答案

技巧是将编码器添加到控制台并确保记录器来自上下文。

private static Logger buildLogger() {

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.reset();
Logger logger = lc.getLogger(henson.class);
logger.detachAndStopAllAppenders();

PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();

ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<>();
ca.setTarget("System.err");
ca.setContext(lc);
ca.setEncoder(ple);
ca.start();

logger.addAppender(ca);

logger.setLevel(Level.DEBUG);
return logger;
}

关于java - 配置 LogBack/ConsoleAppender 以写入 STDERR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859459/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com