我正在通过MDC插入一些变量,但是如果在varback模式中没有使用此var,我想记录一个WARN。有谁知道如何在java代码中检索回归模式? STH。像这样:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
...
...
Logger LOG = LoggerFactory.getLogger(MyTestClass.class);
...
MDC.put("id","thisIsATestId");
String pattern = LOG.getLogbackPattern();
checkPatternAndWarnIfMissingVar(pattern,"id");
...
答案 0 :(得分:4)
这有点难看,这可能表示我们并不打算这样做,但似乎有效:
// Get some internal contexts
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)
LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
// Get the current pattern in the appender.
OutputStreamAppender<ILoggingEvent> consoleapp =
(OutputStreamAppender<ILoggingEvent>) logger.getAppender("console");
// Now check the pattern
PatternLayoutEncoder encoder = (PatternLayoutEncoder) consoleapp.getEncoder();
String pattern = encoder.getPattern();
checkPatternAndWarnIfMissingVar(pattern,"id");
请注意,这假设一个名为&#34; console&#34;的追加器。 appender列表取决于您的配置,可以使用以下方法检索:
Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders();
while (it.hasNext()) {
Appender<ILoggingEvent> app = it.next();
System.out.println( app.getName() );
}
答案 1 :(得分:0)
更新 Henrik 的答案,我让它像这样工作:
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
private String getPattern() {
Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
OutputStreamAppender<ILoggingEvent> consoleAppender =
(OutputStreamAppender<ILoggingEvent>) logger.getAppender("CONSOLE");
PatternLayoutEncoder encoder = (PatternLayoutEncoder) consoleAppender.getEncoder();
return encoder.getPattern();
}