Question

Is there a recommended Log4J2 pattern for logging individual jobs to individual files?

We have a platform that uses Log4J to write logs for individual jobs that run on our platform. We do this by creating a new Logger for each job: logger = Logger.getLogger(getClass().getPackage().getName() + '.' + name + '.' + dateTime);

However, the Usage page in the Log4J2 manual states that in Log4J2 Logger objects are never destroyed until the application is shut down. Does this mean (as I suspect) that our current code will create a large memory leak in Log4J2, and is there a better way to write a temporary object's logs to an individual file in Log4J2?

I'm trying to determine how to do this work. My current best idea is to write a custom Appender that writes to different files based on information in the LogEvent, but that does not seem like the correct way to do this.

 4  45  4
1 Jan 1970

Solution

 0

Log4J2 supports MDCs which are key-value pairs attached to logging events. In each job, set the MDC with job-specific details like name and timestamp before logging.

But I think you may better to don't create new Logger for each job. also you can use dynamic file creation pattern %d{yyyy-MM-dd_HH-mm-ss} or job name within the filename pattern it can be help separate files.

2024-07-11
Ali.Mojtahed