如何在logback中获取所有appender名称

时间:2018-03-05 12:47:58

标签: java logging logback logback-classic

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

2 个答案:

答案 0 :(得分:1)

以下代码将收集当前LoggerContext中的所有appender:

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);
}

答案 1 :(得分:1)

谢谢@glytching。

我找到了一个较短的答案:

LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
for (Logger logger : context.getLoggerList()) {
    for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext();) {
        Appender<ILoggingEvent> appender = index.next();
    }
}