通过node.js中的ID跟踪请求流 [英] tracking request flow by ID in node.js

查看:96
本文介绍了通过node.js中的ID跟踪请求流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的node.js应用程序中,每当我收到请求时,我都希望使用一些唯一的ID标记"它,并能够通过该ID跟踪与此请求相关的所有活动(日志语句).因此,当请求传入时,我将其传递到较低的应用程序层(服务,数据库调用等),我希望能够收集与给定请求ID匹配的所有日志,以重新构建其遍历应用程序的旅程.

In my node.js application whenever I get request I'd like to "stamp" it with some unique ID and be able to track all the activities (log statements) related to this request by this ID. So when request comes in and I pass its handing to lower application layers (services, database calls etc) I want to be able to collect all logs matching given request ID to rebuild its journey through the app.

因此,有了这张照片,我现在使用 request-local 模块,但是它做了一些令我失望的沉重魔力(来自多个请求的日志获得了相同的ID).

So having this picture, I use request-local module now, but it does some heavy magic that has just failed me (logs from multiple requests get the same ID).

代码主要基于Promises(不是普通的旧节点回调),并且我使用更高阶的函数来提供对实际函数的依赖关系(在开始时就构建了应用程序树).

The code is mostly based on Promises (not plain old node callbacks) and I use higher order functions to provide dependencies to my actual functions (with application tree being built during the start).

第一个也是非常明显的解决方案是将该请求ID传递给每个调用的函数,但这是一场灾难,我不愿意这样做.

First and quite obvious solution would be to pass this request ID down to every function called, but it's a disaster and I'm not gonna do that.

您如何(可靠地)进行这种请求跟踪,而无需显式传递此id/context作为所有级别下层函数的额外参数?

How do you (reliably) do that kind of request tracking without explicitly passing this id/context as an extra argument to functions all levels down?

推荐答案

已编辑

该库可以完成这项工作.它是Winston库的包装,因此以相同的方式配置,并且为每个请求生成唯一的ID,并在每个日志中打印出来

This library do the job. It is a wrap of Winston library, so it's configured the same way, and it generates a unique ID for each request and it prints it with each log

https://github.com/davicente/express-logger-unique-req-id

===============

===============

我提出了一种方法,其中ID将根据请求是唯一的,并且您不需要在不同的调用和模块之间传递任何对象(req,id ...).这意味着要使用一个库来创建唯一的ID,我选择了node-uuid,而另一个库则是在不同模块之间共享上下文变量(continuation-local-storage),但要根据请求使用名称空间,以便为所有调用(甚至是异步调用).此外,我包装了Winston库,以便在每个日志中打印请求ID.这样,您就可以跟踪一个请求的所有日志.

I made an approach in which the id will be unique by request and you won't need to pass any object (req, id ...) among the different calls and modules. It implies the use of one library to create unique ids, I chose node-uuid, and another library to share context variables among different modules (continuation-local-storage) but using namespaces by request, in order to keep the id for all the calls (even asyncrhonous ones). Besides, I wrapped Winston library in order to print the request Id in every log. With this you will be able to trace all the logs of one request.

我在此处 https://编写了带有代码示例的完整说明.solidgeargroup.com/express-logging-global-unique-request-identificator-nodejs

这篇关于通过node.js中的ID跟踪请求流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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