Is it possible to retrieve a list of all appenders configured in log4j at run time?
I'll flesh out the scenario a little more. Given the following config how would I retrieve all appenders (stdout and altstdout)?
log4j.rootLogger=error, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.altstdout=org.apache.log4j.ConsoleAppender
log4j.appender.altstdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.altstdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
Working Solution for Log4j 1:
Note: getAllAppenders will get only active log. Not the full list of files defined in your log4j.xml configuration file.
Here's how I could achieve this for setting rwxrwxrwx rights on all log files
If you want access to all appenders configured for all loggers you must do something like this
I don't know why log4j has no method like LogManager.getAllAppenders(), but it looks like
disadvantage.
I want to add something that took me a while to understand. If you look at the figure below (which I copied from here), you can see, that even though the logger
com.foo.bar
will print to the root loggers FileAppender, its appender list is still null. So you cannot get all appenders the logger will write to with the methodlogger.getAllAppenders()
.For this you need to iterate through all the parents also and the root logger seperately. Because you cannot iterate
logger.getParent()
to root logger (root logger returns null - see documentation of getParent()). As far as I know, you have to access the rootLoggers' appenders seperately viaLogger.getRootLogger().getAllAppenders().
This is one what you need
log4j Method getAllAppenders