question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] AsyncLocalStorage loses context between middleware

See original GitHub issue

Information

  • Version: 6.x
  • Packages: all

In v5 this worked correctly and works correctly with vanilla Express.

If you use AsyncLocalStorage (or async_hooks or cls-hooked) in a middleware and then attempt to access the store inside of another middleware or controller down the line, the execution context of the run method is lost between the middlewares and the store is no longer available. Calling next inside of the executing function should keep the executing context.

Example

I’ve created a small repo to reproduce the issue - https://github.com/csnate/tsed-scope

Run npm start to run the TsED server (http://localhost:8080/rest/health). Run npm run express to run the Express server (http://localhost:8080/health). Both are very small and expose a single route that calls 2 middleware. The first middleware starts the AsyncLocalStorage and runs it inside of the first middleware, setting a uuid as “correlation-id” in the store, logs some info to confirm the data is in the store, and then calls next inside of the executing function. The second middleware attempts to read from the store and get the correlation-id and log it.

Here are the logs from the TsED request:

[2021-03-16T08:17:07.960] [INFO ] [TSED] - In TestMiddleware
[2021-03-16T08:17:07.961] [INFO ] [TSED] - In TestMiddleware Async fa163902-37cf-4973-bf57-42a394161c33
[2021-03-16T08:17:07.961] [INFO ] [TSED] - In TestMiddleware Store:  fa163902-37cf-4973-bf57-42a394161c33
[2021-03-16T08:17:07.962] [INFO ] [TSED] - Test2Middleware: store missing

Here are the logs from the Express request:

In testMiddleware
In TestMiddleware Async 60336a85-ef12-4adf-a727-75a7f0220155
In TestMiddleware Store:  60336a85-ef12-4adf-a727-75a7f0220155
Test2Middleware:  60336a85-ef12-4adf-a727-75a7f0220155

I’ve check the TsED code, but have been unable to determine where/how the context is getting lost.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:9

github_iconTop GitHub Comments

1reaction
Romakitacommented, Mar 16, 2021

Here is the right with the Layout:

@Layout({ name: 'custom-layout' })
export class CustomLayout extends BaseLayout {
    public transform(loggingEvent: LogEvent, timezoneOffset?: number | undefined): string {
        const log: any = {
            categoryName: loggingEvent.categoryName,
            level: loggingEvent.level.toString(),
            message: loggingEvent.data.join(' '),
        };
        
        const $ctx = PlatformAsyncHookContext.getStore().getStore() // i know, it's strange...

        if ($ctx?.id) {// but requestId is already added to each log in loggingEvent.data (inspect data to see the field reqId)
            log.correlationId = this.$ctx?.id;
        }

        return JSON.stringify(log);
    }
}

but is really strange to create a CustomLayout to append requestId (correlationId) which is already present for each log generated by Ts.ED.

1reaction
Romakitacommented, Mar 16, 2021

So, how I would access that id inside of a custom Logging Layout? Would something like this work?

No it won’t works because, Layout is not an injectable provider. Logger is an independent project from the Ts.ED framework. Let me find a way to do that.

Read more comments on GitHub >

github_iconTop Results From Across the Web

async_hooks: AsyncLocalStorage losing context #41285
It seems that wrapping it inside setImmediate() makes the context propagate correctly. I'm probably missing some piece and I designed some part ...
Read more >
node.js - asyncLocalStorage loses context in error middleware?
I am trying to use asyncLocalStorage.getStore in an errorMiddleware after the application throws an error. I noticed that asyncLocalStorage.
Read more >
Node.js 14 & AsyncLocalStorage: Share a context between ...
AsyncLocalStorage is used to share data between asynchronous calls. ... with the execution context to call it with the caught error.
Read more >
Logging with Pino and AsyncLocalStorage in Node.js
Proper logging can be the difference between a lousy dump of debug ... is that the function stack and context is lost in...
Read more >
AsyncLocalStorage and Structured Logging in Nest.js
A key piece of information missing from it is its context of execution, such as the name of the service and the method...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found