如何通过Express中的中间件链识别请求(通过ID)。 [英] How to identify request (by ID) through middleware chain in Express.

查看:146
本文介绍了如何通过Express中的中间件链识别请求(通过ID)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express as框架在node.js中开发一个RESTful服务器,目前正在使用Winston作为记录器模块。
该服务器将处理大量的同时请求,对于每个特定请求,使用类似请求ID的跟踪日志条目对我来说非常有用。直接的解决方案就是将ID作为另一条记录信息添加到每个日志条目中,但这将意味着将请求ID传递给服务器使用的每个方法。

I am developping a RESTful server in node.js, using Express as framework, and Winston, for the moment, as logger module. This server will handle a big amount of simultaneous request, and it would be very useful to me to be able to track the log entries for each specific request, using something like a 'request ID'. The straight solution is just to add this ID as another piece of logging information each time I want to make a log entry, but it will mean to pass the 'request ID' to each method used by the server.

我想知道是否有任何node.js / javascript模块或技术,这将允许我以更简单的方式执行此操作,而无需携带每个特定请求的请求ID。 / p>

I would like to know if there is any node.js/javascript module or technique that would allow me to do this in an easier way, without carrying around the request ID for each specific request.

推荐答案

您可以使用快递中每个请求附带的 req

所以你在应用程序中执行的第一个路由是:

You can use req object that does comes with every request in express.
So the first route you would do in your application would be:

var logIdIterator = 0;

app.all('*', function(req, res, next) {
  req.log = {
    id: ++logIdIterator
  }
  return next();
});

然后在快递中的任何地方,您可以访问 id req 对象: req.log.id ;

您仍然需要将一些数据传递给要创建一些日志的函数。实际上,您可能在 req.log 对象中具有日志记录功能,所以这样做将保证只有在访问 req时才会发生日志记录.log 对象。

And then anywhere within express, you can access that id in req object: req.log.id;
You will still need to pass some data into functions that do want to create some logs. In fact you might have logging function within req.log object, so that way it will be guaranteed that logging will happen only when there is access to req.log object.

这篇关于如何通过Express中的中间件链识别请求(通过ID)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆