0

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?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • This does not sound possible, since Log4J will not be able to know in advance the file descriptor to which it must write the logs. It looks like it can only be done programatically, but the log4j API has the tools for that as well. – fge Jan 01 '13 at 11:27
  • OK, so how can I do this programatically, while keeping my application multi-threaded? – Erel Segal-Halevi Jan 01 '13 at 11:40

1 Answers1

3

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

Community
  • 1
  • 1
radai
  • 23,949
  • 10
  • 71
  • 115
  • "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" But this means that I cannot run two instances of that long operation in parallel (in two worker threads)? – Erel Segal-Halevi Jan 01 '13 at 12:50
  • 1
    of course you can - MDC is thread-local, so if you have 2 TXs taking place for 2 different users the logging will go to different files. if you want a single TX (for a single user) to do threading, you will need to carry over your MDC to each new thread you create. if you want 2+ TXs in parallel (unrelated) under the same user, you will need to put user + some unique TX id in the MDC and write your own appender that will group output not only by the user value, but by user+tx id – radai Jan 01 '13 at 13:18