How to get distinct loggers in log4j?
java, log4j
Solution
You could do something like this. First get all loggers from the log manager:
Enumeration<Category> loggers = LogManager.getCurrentLoggers();
Then you can ask each logger for its level:
Level currentLevel = logger.getLevel();
`currentLevel` will be `null` if it has never been explicitly set. So, if the logger was set to a specific level in `log4j.properties`, you will get a non-null value. Else you will get a `null` value. The root logger always reports a level, so that would be a special case. This way, you would not need to parse the `log4j.properties` file.
The only problem is that if somewhere in your code you invoke `setLevel()` on a logger, it will also report non-null and appear on your list. That is because log4j does not know how a level was set, only if it was set at all. To distinguish these two cases, you would still need to parse `log4j.properties`.
Also, keep in mind that this works only on loggers which are currently loaded. So if `com.foo.Bar` was never loaded, you will not see it on your list even if it is explicitly mentioned in `log4j.properties`. Log4J does not know about non-existing loggers which might be created in the future. Again, for this you would need to parse `log4j.properties`.
Problem
If my log4j.properties looks this ``` # General configuration log4j.rootLogger = ERROR, ConsoleAppender # Appender configuration log4j.appender.ConsoleAppender = org.apache.log4j.ConsoleAppender log4j.appender.ConsoleAppender.layout = org.apache.log4j.PatternLayout log4j.appender.ConsoleAppender.layout.ConversionPattern = %5p (%c) %m%n #Other Loggers log4j.logger.com.foo=INFO log4j.logger.com.foo.Bar=DEBUG log4j.logger.org.springframework=INFO ``` Is there an easy way to get just the loggers `com.foo`, `com.foo.Bar`, `root`, and `org.springframework`. And not the specific classes that have been created and inherit the levels (I.E. `com.foo.bar.Baz`? For my purposes I want to create an admin page that displays these loggers and their levels, but not ALL loggers, just the ones that have been directly configured via properties. currently, I am traversing up the parent hierarchy until I come across a logger that has a different level that its parent, but that can hide some configured loggers if they are in the hierarchy and set the same level as something higher up.