what is the NDC logs and how we can use it in our application and what is the significance of that...
views:
37answers:
3NDC stands for "Nested Diagnostic Contexts", it's a feature of log4j. The most common usage of log4j is just to log stuff without any indication of what client request it was part of, with the result that, when your application runs in production with concurrent requests, all the log messages for all the requests are jumbled together in the log file and telling who did what is impossible. NDC allows you to mark log messages as belonging to particular clients so that you can distinguish who is doing what, without having separate loggers for each client.
Nested Diagnostic Contexts are particular to a thread.
Common uses are for recording info per-session (if one thread is used for a session), so you can log the originating client, username etc. and other cross-cutting attributes without:
- passing these attributes through the layers of your application
- explicitly logging them in each log statement. Log4j will output the NDC if
PatternLayout
is suitably configured.
See also Log4j's Mapped Diagnostic Contexts.
Logger are usually statically defined in the code, which make log sometimes hard to understand.
The NDC allows the dynamically push
a parameter that will be displayed in every subsequent log line issued by the thread, until it is pop
ped.
Useful if you want a log like:
[request=x] a
[request=y] a
[request=x] b
[request=x] c
[request=y] b
[request=x] d
[request=y] c
[request=y] d
(Disclaimer: I don't remember the exact formatting)
With just a,b,c,d
it's hard to understand which thread does what. If you push
and pop
the request id dynamically, then it's easier to follow. Can also be used for other kinds of contextual information.