@evanion/nestjs-correlation-id (英语)
在您的 NestJS 微服务中透明地请求追踪 .
调试分布式系统就像用三个不同框的片段解决一个谜题,当一个单一的用户动作触发一个服务链时,你被迫通过猜测时间戳来通过零碎的日志来打猎. @evanion/nestjs-correlation-id 解决此问题的方法是给每个收到的请求附加一个关联ID,并通过您的服务链转发它.
要在不作为函数参数传递的情况下看到标识符的跟踪,以下示例使用 CorrelationService.run 以模拟中间软件通常打开的请求上下文.
import { CorrelationService } from '@evanion/nestjs-correlation-id';
const lines: string[] = [];
const logger = { log: (line: string) => lines.push(line) };
class OrdersService {
constructor(
private readonly correlationService: CorrelationService,
private readonly logger: { log(line: string): void },
) {}
place(order: string) {
const id = this.correlationService.getCorrelationId();
this.logger.log(`Placing ${order} for request ${id}`);
}
}
const correlation = new CorrelationService({
header: 'X-Correlation-Id',
generator: () => crypto.randomUUID(),
});
const orders = new OrdersService(correlation, logger);
correlation.run('storefront-4f1c9a', () => orders.place('order-2026-0042'));
orders.place('order-2026-0043');
lines; // -> ['Placing order-2026-0042 for request storefront-4f1c9a', 'Placing order-2026-0043 for request undefined']
能力
@evanion/nestjs-correlation-id 用途 AsyncLocalStorage 以确保身份识别在同时提出的请求之间保持隔离并生存下去 await 边框.
- 转发页:1
HttpService注册withCorrelation()通过 Axios 截取器发送每一次通话的当前ID . - 上下文预览: 请求链中任何地方都有相关标识——护卫、拦截器、控制器和服务.
- 完全配置: 自定义页眉名称( E)
X-Correlation-Id),ID生成器,以及验证逻辑. - 兼容性:中间软件运行于雀巢JS默认快车平台.
所需经费和安装
一揽子方案仅是无害环境管理,需要20号节点或更新。 用这个 tslib 作为它唯一的运行时间依赖 @nestjs/common 12作为同伴依赖 @nestjs/axios 12作为转发的可选依赖.
npm install @evanion/nestjs-correlation-id
文档
参考和综合指南全文请访问我们的文献网站:
👉 docs.evanion.com/nestjs-correction-id (中文(简体) )
许可证
麻省理工学院