项目场景:
nodejs koa web服务
1、并发请求日志须包含traceId以便方便分析
2、请求周期内用户数据隔离
两种解决办法都可以
- AsyncLocalStorage
用 AsyncLocalStorage 存储 - Context Request
直接在request 中保存
const uuid = require('uuid');
const { AsyncLocalStorage } = require('async_hooks');
const als = new AsyncLocalStorage();
// 在中间件中
app.use(async(ctx, next) => {
// 1 AsyncLocalStorage
const traceId = ctx.request.header['x-trace-id'];
als.enterWith(traceId ? traceId : uuid.v4());
// 2 Context Request
ctx.request._data = {id: uuid.v4()};
// 引用
console.log(`[trace:${als.getStore()}] ->`, ctx.request._data.id) // <----
await next();
});
router.get('/', async(ctx, next) => {
let res = null;
res = await new Promise((resolve, reject) => {
setTimeout(function() {
console.log(`[trace:${als.getStore()}] /=>`, ctx.request._data.id); // <----
resolve(true);
}, 500);
});
});