[logback-user] How do I get a list of configured loggers?
Ceki Gulcu
listid at qos.ch
Tue Nov 11 10:12:24 CET 2008
Hello Gunnar,
Logback and log4j are similar, albeit not identical, in the way they store
loggers. So I can't imagine why in one case you would get only the loggers you
configured and in the other "hundreds" of loggers, unless you search for the
loggers at different times during life cycle of your application. More
precisely, in the log4j case you were probably iterating on the loggers just
after log4j was configured and in the logback case later in the application life
cycle. Was that the case?
Anyway, in logback, you can filter out non-configured loggers with the following
code:
List<String> findNamesOfConfiguredAppenders() {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
List<String> strList = new ArrayList<String>();
for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
if(log.getLevel() != null || hasAppenders(log)) {
strList.add(log.getName());
}
}
return strList;
}
boolean hasAppenders(ch.qos.logback.classic.Logger logger) {
Iterator<Appender<LoggingEvent>> it = logger.iteratorForAppenders();
return it.hasNext();
}
HTH,
Gunnar Hillert wrote:
> How do I get a list of configured loggers (In logback.xml) programmatically?
>
> e.g. I have the following loggers configured in my logback.xml file:
>
> ...
> <logger name="org.springframework.security">
> <level value="DEBUG"/>
> </logger>
> <logger name="org.apache.struts">
> <level value="INFO"/>
> </logger>
> ...
>
> How do I get those loggers? (E.g. I like to dynamically inspect and change
> my setup loggers at runtime)
>
> I was able to do this easily in Log4J but I seem to have issues doing so in
> logback.
>
> I thought I could do:
>
> LoggerContext lc =
> ((ch.qos.logback.classic.Logger)LOGGER).getLoggerContext();
> List<String> strList = new ArrayList<String>();
> Iterator<ch.qos.logback.classic.Logger> it =
> lc.getLoggerList().iterator();
> while(it.hasNext()) {
> Logger log = it.next();
> strList.add(log.getName());
> }
>
> But this basically adds hundreds of loggers but I only want the ones I have
> configured in my logback.xml file.
>
> What do I miss here?
>
> Thanks a lot!
>
> Gunnar
>
>
--
Ceki Gülcü
Logback: The reliable, generic, fast and flexible logging framework for Java.
http://logback.qos.ch
More information about the Logback-user
mailing list