Reputation: 1311
I need to create separate logs for different object instances in my applications. For example if we work with books, i need separate log file for every book. It works fine with log4j2.xml file, but i may have hundreds of such objects in memory and i don't want to create such a long configuration file. I want to create appenders and loggers from code. I looked for working code example and found nothing.
I tried to use RollingFileAppender.createAppender but didn't found how to attach it to logger and failed to get proper values for this function parameters. Please help with working code\configuration how to create separate log files per object property.
Probably it can be done with wildcards in appender\logger names in log4j2.xml or using renderer?
Upvotes: 1
Views: 1856
Reputation: 40036
If splitting log file base on "book" is what you are looking for, instead of creating a very specific appender or configure log4j programmatically to deal with that, you should have a look at MDC.
With proper MDC setup, it should be straight-forward to split log files base on MDC content (e.g. in LogBack, there is a SiftingAppender. I believe there is similar 3rd-party appenders that do the same thing)
Upvotes: 1
Reputation: 36754
You could use the static method #initialize(String contextName, ClassLoader loader, String configLocation)
(see source here) in org.apache.logging.log4j.core.config.Configurator
.
(You can pass null for the class loader.)
Be aware that this class is not part of the public API so your code may break with any minor release.
Upvotes: 0