I am running a Java application in which I am invoking multiple threads, each with some unique names. Now I want to create multiple log files for each of them and the name of the log files should be as the thread names. Is this possible using log4j2. Please help me write log4j2 configuration files.
Thank you in advance.
This can be done with the RoutingAppender. The FAQ page has a good example config.
I agree a RoutingAppender is the way to go. I initially used the routing appender in conjunction with the ${ctx:threadName} lookup where the 'ctx' uses the ThreadContext. I found that I would have to sprinkle in the code a line like this:
While that code works it's not extensible in the design of the code. If I were to add a new
java.lang.Runnable
to the code base, I would have to also include that line.Rather, the solution seems to be to implement the 'org.apache.logging.log4j.core.lookup.StrLookup' and register the
@Plugin
with thePluginManager
Like this:Class:
ThreadLookup
Configuration: log4j2.xml (
packages
attribute of theConfiguration
registers the@Plugin
with thePluginManager
)