3

我读了这篇文章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));
  }
4

1 回答 1

7

我解决问题。问题是我由于bodyparser中间件而失去了上下文。我在设置上下文之前更改了该中间件,现在可以了。曾是:

app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set("requestId", uuid());
    next();
  });
});

// body parser
app.use(
  bodyParser.json({
    limit: "10mb"
  })
);

改变:

// body parser
app.use(
  bodyParser.json({
    limit: "10mb"
  })
);

app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set("requestId", uuid());
    next();
  });
});

现在好了)

于 2020-10-14T15:16:38.840 回答