Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
phaddius opened this issue Jan 17, 2019 · 2 comments
Open

Comments

@phaddius
Copy link

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
Copy link

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
Copy link

quezak commented Jun 13, 2019

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);
        });
    };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants