Implementing a Java-Like Mapped Diagnostic Context (MDC) for Logging Within an Express Application
Common Java loggers (Log4j, Logback, etc.) implement a Mapped Diagnostic
Context (MDC), i.e. a simple map that is associated to the current thread. This
allows for storing contextual information to be logged together with whatever
message is emitted by the application.
Typically one will want to log:
- which user/session is responsible for the currently logged statement (for audit purposes)
- which request led to a given action (for debugging purposes, how actions are correlated one to each-other)
Being fully asynchronous, nodejs does not allow for attaching such a context to
a thread. Fortunately, some smart people are currently
introducing into node
a way of following asynchronous execution stacks, to which a context map can be
For now, a shim is available, and node-continuation-local-storage already allows for persisting contexts.
You can find the example on my Github account.
blog comments powered by Disqus