[BUG] AsyncLocalStorage loses context between middleware
See original GitHub issueInformation
- 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:
- Created 3 years ago
- Comments:9
Here is the right with the Layout:
but is really strange to create a CustomLayout to append requestId (correlationId) which is already present for each log generated by Ts.ED.
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.