Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you differentiate log4j sessions in a log file from copies of the same web-app?

There is only one file. And it is written simultaneously as web app copies run.

How do you filter only one session log messages from other log lines?

like image 434
EugeneP Avatar asked May 04 '10 08:05

EugeneP


3 Answers

Using a servlet filter with either NDC or MDC information is the best way I've seen. A quick comparison of the two is available at http://wiki.apache.org/logging-log4j/NDCvsMDC.

I've found MDC has worked better for me in the past. Remember that you'll need to update your log4j properties file to include whichever version you prefer (pattern definitions at http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html).

A full example of configuring MDC with a servlet filter is available at http://veerasundar.com/blog/2009/11/log4j-mdc-mapped-diagnostic-context-example-code/.

A slightly easier to configure, but significantly inferior option: You could opt to just print out the thread ID (via the properties file) for each request and make sure that the first thing you log about each request is a session identifier. It isn't as proper (or useful), but it can work for low-volume applications.

like image 199
John D Avatar answered Sep 21 '22 16:09

John D


You could set a context message including the identifier of the specific app instance using org.apache.log4j.NDC, like this:

String appInstanceId = "My App Instance 1";
org.apache.log4j.NDC.push(appInstanceId);
// handle request
org.apache.log4j.NDC.clear();

You can set up the context during the initialization of your web app instance, or inside the doPost() method of your servlets. As its name implies, you can also nest contexts within contexts with multiple push calls at different levels.

See the section "Nested Diagnostic Contexts" in the Log4J manual.

like image 43
Péter Török Avatar answered Sep 19 '22 16:09

Péter Török


Here is a page that sets up an MDC filter for web-app -> http://rtner.de/software/MDCUserServletFilter.html

Being a servlet filter it will free you from managing MDC/NDC in each of your servlets.

Of course, you should modify it to save information more pertinent to your web-app.

like image 42
Alexander Pogrebnyak Avatar answered Sep 18 '22 16:09

Alexander Pogrebnyak