Reputation: 246
I run a Java webapp deployed in Tomcat. We use commons-logging
as a wrapper around log4j v1.2.16
We have many concurrent requests hitting the server and do not wish to debug/trace log every request. However, for certain users we wish to trace their transactions for debugging reasons. We maintain a list, driven from the database, of which users to trace. When the request hits, we check our list to see if we should trace the.
They pass in their username in the GET string and we have no problem getting this, adding it to the MDC
and then printing it before the log message in the file by way of a ConversionPattern
.
We now wish to create a file for each user we have a trace on and my solution to this was to create a custom extension to RollingFileAppender
which all logging is directed at.
If the log level is trace
we check MDC.get("traceOn")
to see if we should output.
I then do the following (dirty example):
String file = "/var/log/tomcat6/application/trace/"+MDC.get("username")+".log";
this.setFile(file);
this.activateOptions();
super.doAppend(event);
I know that the MDC is on a per-thread basis, but is it safe to run this in production with 10 concurrent threads logging and potentially writing to their own files?
If not - how could I achieve the same thing - writing to multiple log files based on the MDC (whether we should log at all, and the filename to use if so)?
Upvotes: 0
Views: 1316
Reputation: 4824
log4j is thread-safe. Log4j components are designed to be used in heavily multithreaded systems. Reference: https://logging.apache.org/log4j/1.2/faq.html#a1.7
Automatic Reconfiguration:
When configured from a File, Log4j has the ability to automatically detect changes to the configuration file and reconfigure itself. If the monitorInterval attribute is specified on the configuration element and is set to a non-zero value then the file will be checked the next time a log event is evaluated and/or logged and the monitorInterval has elapsed since the last check. The example below shows how to configure the attribute so that the configuration file will be checked for changes only after at least 30 seconds have elapsed. The minimum interval is 5 seconds.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="30">
...
</Configuration>
Reference: http://logging.apache.org/log4j/2.x/manual/configuration.html
Upvotes: 1