# @dazn/lambda-powertools-middleware-correlation-ids 中文文档

规范地址：https://npmcn.com/package/%40dazn/lambda-powertools-middleware-correlation-ids/

版本：1\.29\.0
npm 元数据更新时间：2025-12-04T09:10:00.286Z
中文译文更新时间：2026-11-11T16:56:51.888Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40dazn/lambda-powertools-middleware-correlation-ids
原文对照：https://npmcn.com/package/%40dazn/lambda-powertools-middleware-correlation-ids/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：399 kB，39 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2019-07-24T09:47:14.327Z
- 最新版本发布：2021-05-04T19:23:11.548Z
- 近 30 天下载量：6410（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：25（近 12 个月 0 个）

## 中文简介

从入境事件获取相关ID的中端软件

## 安装

```sh
npm install @dazn/lambda-powertools-middleware-correlation-ids
```

也可以使用：`pnpm add @dazn/lambda-powertools-middleware-correlation-ids`、`yarn add @dazn/lambda-powertools-middleware-correlation-ids`、`bun add @dazn/lambda-powertools-middleware-correlation-ids`

## README

# 羊肉-动力工具-中相相接器

A 类 [中边](https://github.com/middyjs/middy) 从引用事件提取相关 ID 的中间软件,并将其存储在 `@dazn/lambda-powertools-correlation-ids` 软件包.

主要特点:

-   存储与 `@dazn/lambda-powertools-correlation-ids` 软件包
    
-   支持 API 网关事件( HTTP 头)
    
-   支持 SNS 事件( 消息属性)
    
-   支持 SQS 事件(从 SNS 发布时有原始消息发送或没有原始消息发送的信息属性)
    
-   支持 Kinesis 事件(详情见下文)
    
-   支持直接引用和 Step 函数任务(中间软件寻找一个 `__context__` jSON 事件中的财产)
    
-   使用 Lambda 请求ID 初始化关联ID
    
-   抓取任何带有前缀的东西 `x-correlation-`
    
-   捕获 `User-Agent` 来自 API 网关事件
    
-   抓取或初始化 `debug-log-enabled` 基于配置(见下文)的决定,以确保在上游决定之后引用,从而能够调试一小部分引用的日志
    

## 开始

从国家预防机制安装: `npm install @dazn/lambda-powertools-middleware-correlation-ids`

或者,如果使用模板的话 `@dazn/lambda-powertools-pattern-basic` 然后这个会被配置给你.

## API 密码

接受以下形状的配置对象:

```js
{
  sampleDebugLogRate: double [between 0 and 1]
}
```

```js
const middy = require('middy')
const correlationIds = require('@dazn/lambda-powertools-middleware-correlation-ids')

const handler = async (event, context) => {
  return 42
}

module.exports = middy(handler)
  .use(correlationIds({ sampleDebugLogRate: 0.01 }))
}
```

这个中间器件常被与 `@dazn/lambda-powertools-middleware-sample-logging` 执行样本记录的中间软件。 这是 **建议** 您使用 `@dazn/lambda-powertools-pattern-basic` 用于在引用的1%时调试日志.

## 日志和转发关联ID

**说明**数字 : _这不适用于 `Kinesis` 财务报告和审定财务报表 `SQS` 事件源,其引用事件包含有一批记录,需要不同的处理. 详情见下文._

一旦您包裹了您的处理器代码, 当 :

-   输入 `@dazn/lambda-powertools-logger` 日志
-   当您使用 HTTP 请求时 `@dazn/lambda-powertools-http-client` HTTP 客户端
-   当您与来自此工程的 AWS SDK 客户端交互时

如果你正在使用这些配套的软件包,那么关联的ID就会通过你的功能. 但是,如果想要增加现有的关联ID,那么您也可以在与该组合的混合中添加新的关联ID `@dazn/lambda-powertools-correlation-ids` 软件包.

## Kinesis 和 SQS 事件的日志和转发关联ID

由于Kinesis和SQS都支持分批,这意味着引用事件可以包含多个记录. 每一个记录都有自己的相关ID.

为了解决这个问题,这个中间软件将提取每个记录的相关ID并提供给您,同时为每个记录创建一个专门的日志实例. 如何发生这取决于事件源.

HTTP客户端以及来自此工程的AWS SDK客户端都有一个覆盖功能,可以让您通过这些记录特有的相关ID.

### 键盘

对于动能事件,中间器件会为每个记录做以下操作:

1.  Unzip; Base64 解码; 解析为 JSON; 从记录正文中提取相关ID( 在 `__context__` (b) 财产).
    
2.  创建实例 `CorrelationIds` (从 `@dazn/lambda-powertools-correlation-ids` 包),以持有所提取的关联ID.
    
3.  创建实例 `Log` (从 `@dazn/lambda-powertools-logger` 包),其中提取的关联ID已经烤入.
    
4.  在解析过的 JSON 对象上附加关联的ID和日志 .
    
5.  包含第4步中解析的 JSON 对象 `context.parsedKinesisEvents`。 。 。 .
    

在使用来自动力工具包的HTTP客户端和AWS SDK客户端时,您需要将它们列为选项或使用超载方法之一. 例如:

![](https://npmcn.com/package/%40dazn/lambda-powertools-middleware-correlation-ids/docs/images/kinesis_middleware_illustrated.png)

此处为示例函数.

```javascript
const Log = require('@dazn/lambda-powertools-logger')
const SNS = require('@dazn/lambda-powertools-sns-client')
const wrap = require('@dazn/lambda-powertools-pattern-basic')

module.exports.handler = wrap(async (event, context) => {
  const events = context.parsedKinesisEvents

  // you can still use the global Log instance, it'll still have the request ID for
  // the current invocation, but it won't have any of the correlation IDs for the
  // individual records
  Log.debug('received Kinesis events', { count: events.length })

  await Promise.all(events.map(evt => {
    // each parsed kinesis event has a `logger` attached to it, with the correlation IDs
    // specific for that record
    evt.logger.debug('publishing kinesis event as SNS message...')

    const req = {
      Message: JSON.stringify(evt),
      TopicArn: process.env.TOPIC_ARN
    }

    // the SNS client has an overload method for publish, which lets you pass the
    // correlation IDs specific to this parsed kinesis event
    return SNS.publishWithCorrelationIds(evt.correlationIds, req).promise()
  }))
})
```

### 质量

对于SQS事件,中间器件会为每张记录做以下操作: 1

1.  从信件 attribtues 中提取相关 ID .
    
2.  创建实例 `CorrelationIds` (从 `@dazn/lambda-powertools-correlation-ids` 包),以持有所提取的关联ID.
    
3.  创建实例 `Log` (从 `@dazn/lambda-powertools-logger` 包),其中提取的关联ID已经烤入.
    
4.  在 SQS 原始记录对象中附加相关的ID和日志 .
    

在使用来自动力工具包的HTTP客户端和AWS SDK客户端时,您需要将它们列为选项或使用超载方法之一. 这与上面的"克尼西斯"例子类似. 以下是一个示例函数:

```javascript
const Log = require('@dazn/lambda-powertools-logger')
const SNS = require('@dazn/lambda-powertools-sns-client')
const wrap = require('@dazn/lambda-powertools-pattern-basic')

module.exports.handler = wrap(async (event, context) => {
  // you can still use the global Log instance, it'll still have the request ID for
  // the current invocation, but it won't have any of the correlation IDs for the
  // individual records
  Log.debug('received SQS events', { count: event.Records.length })

  await Promise.all(event.Records.map(record => {
    // each SQS record has a `logger` attached to it, with the correlation IDs
    // specific for that record
    record.logger.debug('publishing SQS record as SNS message...')

    const req = {
      Message: JSON.stringify(record),
      TopicArn: process.env.TOPIC_ARN
    }

    // the SNS client has an overload method for publish, which lets you pass the
    // correlation IDs specific to this SQS record
    return SNS.publishWithCorrelationIds(record.correlationIds, req).promise()
  }))
})
```

## 常见问题

### @dazn/lambda-powertools-middleware-correlation-ids 是什么？

从入境事件获取相关ID的中端软件

### 如何安装 @dazn/lambda-powertools-middleware-correlation-ids？

在项目目录运行 npm install @dazn/lambda-powertools-middleware-correlation-ids，或使用 pnpm add / yarn add / bun add。

### @dazn/lambda-powertools-middleware-correlation-ids 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @dazn/lambda-powertools-middleware-correlation-ids 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @dazn/lambda-powertools-middleware-correlation-ids 可以商用吗？

@dazn/lambda-powertools-middleware-correlation-ids 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @dazn/lambda-powertools-middleware-correlation-ids 的下载量有多少？

根据 npm 官方下载统计，@dazn/lambda-powertools-middleware-correlation-ids 在 2026/10/12 – 2026/11/10 这 30 天内被下载 6,410 次，日均约 214 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @dazn/lambda-powertools-middleware-correlation-ids 还在维护吗？

最新版本 1\.29\.0 发布于 2021/05/05（5 年前）；至今共发布 25 个版本，其中过去 12 个月发布了 0 个；首次发布于 2019/07/24。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

