Reputation: 36793
I have a Java server (based on Socket.IO for Java, but that's not part of the question) that accepts requests from web clients, does some calculations, and sends them back the results.
The server uses some libraries, that use log4j for logging.
Since the calculations are long, I want to send to the clients, not only the final results, but also the logs.
Of course I want to send each client, only the log lines that are relevant to its request.
So, my question is: how can I configure log4j, such that all logs generated during a specific function-call go to a specific logger?
Upvotes: 0
Views: 248
Reputation: 24192
yes, its possible. 1st you need to become familiar with the concept of MDC (Mapped Diagnostic Context) - basically its a per-thread logging context (read - hashmap) where you store stuff. log4j can be configured to send logging output to different destinations based on MDC values - so you could have each user's log output sent to a file named after the user. so what you'd do is set the username (or some identifier) in the MDC when you start the long operation, all of the operation's logging will go into a specific location (file, depending on the logger configured) and then clear the MDC when the op is done.
there's a 2-part tutorial for using MDC here and here.
ideally i'd also write my own log4j logger for this purpose, as was suggested here: Using MDC in log4j to dynamically name the log file
Upvotes: 3