如何使用express来保存Node JS应用程序中的请求上下文?

我的请求对象包含一个唯一的ID,每个日志都在我的应用程序中必须有。这个ID还必须传播到我从后端调用的任何API现在,我将请求对象传递到任何地方。 这显然不是一个理想的解决scheme。有没有什么build议?

代码stream

客户端——->服务器(生成请求ID,使用这个所有日志)—–>传递请求ID到任何api调用

码:

app.use(function(req,res,next) { logger.info("My message",req); }); 

您可以使用continuation-local-storage模块。 还有一个request-local模块,它只是continuation-local-storage之上的一个小层。 不要指望continuation-local-storage永远是完美的,尽pipe…你会碰到cls上下文无效的边缘情况。

这是一个使用continuation-local-storage模块的修改解决scheme。

这是我的context模块。 到目前为止,只有在请求中没有收到path,请求时间和关联ID的情况下才会生成path。

 'use strict'; const continuation = require('continuation-local-storage'); const cuid = require('cuid'); const appName = require('config').get('app_name'); class Context { static setup(req, res, next) { const session = continuation.createNamespace(appName); session.run(() => { session.set('context', new Context(req)); next(); }); } constructor(req) { this.path = req.path; this.corrId = req.headers['x-correlation-id'] || cuid(); this.requestTime = Date.now(); } static current() { return continuation.getNamespace(appName).get('context'); } } module.exports = Context; 

我的app.js包括:

 const Context = require('./context'); app.use(Context.setup); 

之后,任何代码都可以调用Context.current()来获取Express请求的当前上下文。 我将使用它来进行一致的日志logging。