I'm using Express and I need to access some data that it is on the request (headers, cookies, etc) every time I use the log to debug and trace my app.
With other languages (ie: Java) I have the "Thread Context" where I can put that data, and so access it whenever I log something. But with NodeJS there is no such thing, as far as I know, because we have only one thread.
I'm trying to avoid passing the req
variable in every function so I can log that info.
Is there a node or expressjs feature that let me get the data anywhere?
The request context keeps track of the request-level data during a request. Rather than passing the request object to each function that runs during a request, the request and session proxies are accessed instead.
public class RequestContext extends Object. Context holder for request-specific state, like current web application context, current locale, current theme, and potential binding errors. Provides easy access to localized messages and Errors instances.
Have a look at Continuation Local Storage, it implements something similar to thread context for asynchronous call chains: https://github.com/othiym23/node-continuation-local-storage
Also there are efforts to build asynchronous local storage as a standardized feature into javascript itself, but they are still at a very early stage: TC39 Zone Proposal https://docs.google.com/presentation/d/1H3E2ToJ8VHgZS8eS6bRv-vg5OksObj5wv6gyzJJwOK0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With