skonves / express-http-context

Get and set request-scoped context anywhere
MIT License
299 stars 26 forks source link

Question: how to get something like this, but for non-requests (eg jobs) #33

Open phaddius opened 5 years ago

phaddius commented 5 years ago

This looks amazing, and I plan on using it to allow better correlation of logs in my system. I know it only works with express, and specifically http requests. However, I also have many scheduled jobs that I'd like to be able to trace with a shared context, shared logger, or shared correlation id. CLS is new to me, so my question is, is this at all possible outside the context of http requests and express? Any pointers in the right direction would be greatly appreciated!

rohitsud commented 5 years ago

Are the jobs executing within the context of the same node process? If so, you can use CLS to track the context (assuming that all your middleware etc support CLS). If they are implemented across processes, then this cannot be used.

quezak commented 5 years ago

If you look in this lib's source code, it's just a simple wrapper for cls-hooked. I went with just using cls-hooked directly, with a similar custom http request adapter, and a separate "context wrapper" for any function that's called externally outside Express.

My main use case for that are task consumer functions for RabbitMQ. I also do a trick to wrap the describe and it unit test functions -- to add tags to the test names, and then the logs are tagged with them, instead of the usual http req id.

/** Use this to wrap a whole externally-called function (e.g. task handler) in a context. */
export function contextWrapper<A extends any[], R extends any>(
    // some initial context params,
    fn: (...args: A) => R,
): (...args: A) => R {
    return (...args: A) => {
        return CONTEXT_NS.runAndReturn(() => {
            // setContext(...);
            return fn(...args);
        });
    };
}