0
votes

I use log4j 2.9

I have file appenders configured in log4j2.xml.

For example :

 all_log_appender, device_appender, sql_appender

all appenders log in different files.

what is a correct way to choose my appenders at runtime in order to decice where (in which file) to log?

To be honest I can't find examples in the documentation. I also tried to extend Logger class but as I understand it's not correct to extend log4j2 logger class because "some layouts require Log4j to walk the stacktrace to report which class and line in your code from the logger was called from"

I can't find any examples how to choose appender at runtiime.

Could you give me a simple example please?

1

1 Answers

3
votes

This can be accomplished in configuration (no custom code required) by using the Routing Appender built in to Log4j2.

This appender can route log events to a set of predefined appenders or it can dynamically add new appenders if necessary. This stackoverflow answer has examples and links to other examples.

The manual page has three examples, but the FAQ page ("How do I dynamically write to separate log files?") has an example that uses the ThreadContext map to control which log file subsequent events (in the current thread) get logged to. (See also this example on StackOverflow.)

Instead of the ThreadContext, it is also possible (see LOG4J2-1015) to route based on log event Markers, so the application can specify on a per-event basis which file appender the event is routed to. See this StackOverflow answer for an example that routes based on markers.