# @elastic/ecs-helpers 中文文档

规范地址：https://npmcn.com/package/%40elastic/ecs-helpers/

版本：2\.1\.1
npm 元数据更新时间：2026-09-25T13:38:11.560Z
中文译文更新时间：2026-11-13T10:34:15.030Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40elastic/ecs-helpers
原文对照：https://npmcn.com/package/%40elastic/ecs-helpers/?lang=original
项目主页：https://github.com/elastic/ecs-logging-nodejs/blob/main/helpers/README.md
源码仓库：https://github.com/elastic/ecs-logging-nodejs

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

- 包体积（解压后）：26.3 kB，6 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- Node.js 要求：\>=10
- 运行依赖：0 个
- 首次发布：2020-02-11T07:13:31.401Z
- 最新版本发布：2023-10-31T16:58:04.987Z
- 近 30 天下载量：2978422（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：12（近 12 个月 0 个）

## 中文简介

ecs-logb-nodejs 帮助者

## 安装

```sh
npm install @elastic/ecs-helpers
```

也可以使用：`pnpm add @elastic/ecs-helpers`、`yarn add @elastic/ecs-helpers`、`bun add @elastic/ecs-helpers`

## README

![](https://www.elastic.co/static-res/images/elastic-logo-200.png)

# @ elastic/ ecs- 帮助器

[![Build Status](https://apm-ci.elastic.co/buildStatus/icon?job=apm-agent-nodejs%2Fecs-logging-nodejs-mbp%2Fmain)](https://apm-ci.elastic.co/job/apm-agent-nodejs/job/ecs-logging-nodejs-mbp/job/main/) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/)

帮别人的人 [ecs-logb-nodejs 软件包](https://npmcn.com/package/%40elastic/)你应该 不直接使用此软件包.

## 安装

```sh
npm install @elastic/ecs-helpers
```

## API 密码

### `version`

目前支持的版本 [弹性通用外观](https://www.elastic.co/guide/en/ecs/current/index.html)。 。 。 .

### `formatError(obj, err) -> bool`

添加函数 [ECS 错误字段](https://www.elastic.co/guide/en/ecs/current/ecs-error.html) 给定的 `Error` 对象。 如果给定的话, 它返回真实 `err` 错误 对象可以处理.

```js
const { formatError } = require('@elastic/ecs-helpers')
const logRecord = { msg: 'oops', /* ... */ }
formatError(logRecord, new Error('boom'))
console.log(logRecord)
```

将显示:

```js
{
  msg: 'oops',
  error: {
    type: 'Error',
    message: 'boom',
    stack_trace: 'Error: boom\n' +
      '    at REPL30:1:26\n' +
      '    at Script.runInThisContext (vm.js:133:18)\n' +
      // ...
  }
}
```

ECS 日志库通常使用此程序自动处理 `err` 元数据字段传递到一个日志语句。 举个例子. `log.warn({err: myErr}, '...')` 对于皮诺, `log.warn('...', {err: myErr})` 为温顿.

### `formatHttpRequest(obj, req) -> bool`

用 http 请求数据增强 ECS 对象的函数 . 给定的请求对象, `req`,必须是以下之一:

-   节点.js的核心 [`http.IncomingMessage`](https://nodejs.org/api/all.html#http_class_http_incomingmessage), (中文(简体) ),
-   [Express 请求对象](https://expressjs.com/en/5x/api.html#req) 延伸来信,或
-   (单位:千美元) [hopi 请求对象](https://hapi.dev/api/#request)。 。 。 .

如果给定的函数返回真 `req` 是一个请求对象 它可以 进程。 请注意,目前这显然不处理 [`http.ClientRequest`](https://nodejs.org/api/all.html#http_class_http_clientrequest) 从 `http.request()`。 。 。 .

```js
const http = require('http')
const { formatHttpRequest } = require('@elastic/ecs-helpers')

http.createServer(function (req, res) {
  res.end('hi')

  const obj = {}
  formatHttpRequest(obj, req)
  console.log('obj:', JSON.stringify(obj, null, 4))
}).listen(3000)
```

运行此并请求通过 `curl http://localhost:3000/` 将 打印接近 :

```
obj: {
    "http": {
        "version": "1.1",
        "request": {
            "method": "get",
            "headers": {
                "host": "localhost:3000",
                "accept": "*/*"
            }
        }
    },
    "url": {
        "full": "http://localhost:3000/",
        "path": "/"
    },
    "client": {
        "address": "::1",
        "ip": "::1",
        "port": 61969
    },
    "user_agent": {
        "original": "curl/7.64.1"
    }
}
```

### `formatHttpResponse(obj, res)`

用 http 响应数据增强 ECS 对象的函数 . 给定的请求对象, `req`,必须是以下之一:

-   节点.js的核心 [`http.ServerResponse`](https://nodejs.org/api/all.html#http_class_http_serverresponse), (中文(简体) ),
-   [Express 响应对象](https://expressjs.com/en/5x/api.html#res) 扩展服务器响应,或
-   (单位:千美元) [霍比语name **请求** 对象](https://hapi.dev/api/#request)

如果给定的函数返回真 `res` 是一个反应对象,它可以 进程。 请注意,目前这显然不处理 [`http.IncomingMessage`](https://nodejs.org/api/all.html#http_class_http_incomingmessage) 这就是我们的观点 [“答复”事件](https://nodejs.org/api/all.html#http_event_response) 页:1 [客户端 `http.request()`](https://nodejs.org/api/all.html#http_http_request_options_callback)

```js
const http = require('http')
const { formatHttpRequest } = require('@elastic/ecs-helpers')

http.createServer(function (req, res) {
  res.setHeader('Foo', 'Bar')
  res.end('hi')

  const obj = {}
  formatHttpResponse(obj, res)
  console.log('obj:', JSON.stringify(obj, null, 4))
}).listen(3000)
```

运行此并请求通过 `curl http://localhost:3000/` 将 打印接近 :

```
rec: {
    "http": {
        "response": {
            "status_code": 200,
            "headers": {
                "foo": "Bar"
            }
        }
    }
}
```

## 许可证

该软件根据 [Apache 2 许可证](https://npmcn.com/package/%40elastic/ecs-helpers/LICENSE)。 。 。 .

## 常见问题

### @elastic/ecs-helpers 是什么？

ecs-logb-nodejs 帮助者

### 如何安装 @elastic/ecs-helpers？

在项目目录运行 npm install @elastic/ecs-helpers，或使用 pnpm add / yarn add / bun add。

### @elastic/ecs-helpers 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/elastic\_\_ecs-helpers 是否存在。

### @elastic/ecs-helpers 支持 ESM 还是 CommonJS？

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

### @elastic/ecs-helpers 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=10。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @elastic/ecs-helpers 可以商用吗？

@elastic/ecs-helpers 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @elastic/ecs-helpers 的下载量有多少？

根据 npm 官方下载统计，@elastic/ecs-helpers 在 2026/10/13 – 2026/11/11 这 30 天内被下载 2,978,422 次，日均约 99,281 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @elastic/ecs-helpers 还在维护吗？

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

