Feature request - add generic request context object
eugene-kim opened this issue · 5 comments
Hello,
Thank you for the wonderful library. It's helped a bunch in terms of zeroing in on relevant log messages for a single request.
I have a feature request and was wondering what your thoughts might be around opening up cls-rtracer
to have a generic request context object. Rather than simply providing an id that exists throughout the lifetime of the request, there's also a request context object that one can access and put in whatever they want.
Example use case:
Applications that have authorized actions can store the authorized account's id in the request context once authorized. This allows apps to always log an account_id
in a single place when relevant, making tracing all of an account's actions very convenient.
Thanks for the positive feedback.
I think requestIdFactory
option added in #40 could be used to achieve what you have described. This feature allows to use an arbitrary JS value, including objects, as the request id. So, you could write a function that would create objects with a context property along with a UUID v1 id (of course, any other id generation algorithm could be used).
@puzpuzpuz while requestIdFactory
looks as if it can be used to create a generic request id type, I don't think it completely addresses the use case described. The requestId
is something that should be instantiated as soon as possible during the request's lifecycle. With something like authenticated requests, the authentication may not occur until a later point in the request's lifecycle, so having cls-tracer
expose something like setContext
or addContext
to update the context object when appropriate would provide the desired flexibility.
Nothing prevents the context object to be empty initially and then the later middlewares/plugins/handlers could be simply reading and updating the context when necessary. I know that it sounds like a workaround, but the goal of cls-rtracer
is to solve the problem of request tracing, so that's why its API is kept minimal and focused on the problem.
In general, what you're describing is a general-purpose CLS API, which is what cls-rtracer
builds upon. It may be a good option to use AsyncLocalStorage
directly in your app, rather than dealing with the requestIdFactory
workaround. Performance-wise, there should be no noticeable impact in having multiple AsyncLocalStorage
instances vs having a single one. This way you'll get an API close to what was described in this issue.
Does it make sense to go with one of those options in your case?
Hi @puzpuzpuz understood. In that case I may have to look into using AsyncLocalStorage myself. Thanks for the response!
@eugene-kim please let me know if you run into any issues or unclear documentation for AsyncLocalStorage
, as the API is relatively new. Core team would appreciate such feedback from developers.