我读了这篇文章AsyncLocalStorage for Easy Context Passing in Node.js
我尝试在日志中获取 logId,但我不能,因为asyncLocalStorage.getStore()返回未定义。看来 MyLogger 类中的上下文丢失了。怎么解决呢?
这是我的快递应用程序
const asyncLocalStorage = new AsyncLocalStorage();
app.use((req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set("requestId", uuid());
next();
});
});
module.exports.asyncLocalStorage = asyncLocalStorage;
Run Code Online (Sandbox Code Playgroud)
这是 MyLogger 类
static log(logId, className, text) {
const { asyncLocalStorage } = require("../server.js");
const store = asyncLocalStorage.getStore()
console.log(this._getBaseStaticLog(logId, logTypes.LOG, text, className));
}
Run Code Online (Sandbox Code Playgroud)