1

如何在使用 logback 时获取已在 Java 中的 List 中设置的所有 appender 名称的列表。

4

2 回答 2

7

以下代码将收集当前的所有附加程序LoggerContext

private Map<String, Appender<ILoggingEvent>> getAppendersMap() {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();


    Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
    for (Logger logger : loggerContext.getLoggerList()) {

        Iterator<Appender<ILoggingEvent>> appenderIterator = logger.iteratorForAppenders();
        while (appenderIterator.hasNext()) {
            Appender<ILoggingEvent> appender = appenderIterator.next();
            if (!appendersMap.containsKey(appender.getName())) {
                appendersMap.put(appender.getName(), appender);
            }
        }
    }

    return appendersMap;
}

然后,您可以像这样列出名称:

Map<String, Appender<ILoggingEvent>> appendersMap = getAppendersMap();

for (String key : appendersMap.keySet()) {
    logger.info("appender name = {}", key);
}
于 2018-03-05T12:54:10.927 回答
3

谢谢@glytching。

我找到了一个更简短的答案:

LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
    for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext();) {
        Appender<ILoggingEvent> appender = index.next();
    }
}
于 2018-03-06T10:59:33.670 回答