如何为Node.js应用的ECS Winston日志添加自定义字段?
解决方案
1. 添加ECS标准字段(如服务名称)
ECS格式本身定义了service.name这类标准字段,@elastic/ecs-winston-format支持直接通过配置参数传入这些字段,无需额外处理:
const winston = require('winston') const ecsFormat = require('@elastic/ecs-winston-format') const logger = winston.createLogger({ format: ecsFormat({ // 配置ECS标准的服务信息 service: { name: 'my-node-api-service', version: '1.0.0', environment: 'production' }, // 可额外添加其他ECS标准字段,比如主机信息 host: { hostname: 'api-server-01' } }), transports: [new winston.transports.Console()] }) logger.info('user login successful', { userId: '12345' }) logger.error('database connection failed', { err: new Error('connection timeout') })
运行后,日志会自动包含service.name、service.version等ECS标准字段,同时保留原有错误信息、日志级别等默认ECS字段结构。
2. 添加自定义非标准字段
如果需要添加ECS规范外的自定义字段,可以通过winston.format.combine结合自定义格式化函数实现,这些字段会被自动放入ECS的labels对象中(符合ECS规范的自定义字段存放规则):
const winston = require('winston') const ecsFormat = require('@elastic/ecs-winston-format') const logger = winston.createLogger({ format: winston.format.combine( // 自定义添加业务字段 winston.format(info => { info.requestId = 'req-789xyz'; info.team = 'backend'; return info; })(), // 应用ECS格式 ecsFormat({ service: { name: 'my-node-api-service' } }) ), transports: [new winston.transports.Console()] }) logger.info('order created', { orderId: '67890' })
此时日志输出中的labels字段会包含requestId和team,同时完全保留原有ECS格式的结构。
关键说明
- 优先用ECS标准字段:如果要添加的信息属于ECS定义范畴(如服务、主机、事件等),直接通过
ecsFormat配置参数传入,日志结构更规范。 - 自定义字段归到labels:非ECS标准的自定义字段会被自动归类到
labels对象下,避免污染ECS核心字段结构。
内容的提问来源于stack exchange,提问作者ninchicken
相关产品推荐
相关产品推荐

