我读了这篇文章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;
这是 MyLogger 类
static log(logId, className, text) {
const { asyncLocalStorage } = require("../server.js");
const store = asyncLocalStorage.getStore()
console.log(this._getBaseStaticLog(logId, logTypes.LOG, text, className));
}