如何获取在使用logback时在Java中的List中设置的所有appender名称的列表。
答案 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();
}
}