这是之前系列文章:
-  
Elasticsearch:Node.js ECS 日志记录 - Pino
 -  
Elasticsearch:Node.js ECS 日志记录 - Winston
 
中的第三篇文章。在今天的文章中,我将描述如何使用 Morgan 包针对 Node.js 应用进行日子记录。此 Morgan Node.js 软件包为 morgan 日志中间件(通常与 Express 一起使用)提供了一个格式化程序,与 Elastic Common Schema (ECS) 日志记录兼容。结合 Filebeat 发送器,你可以在 Elastic Stack 中的一处监控所有日志。
设置
安装
npm install @elastic/ecs-morgan-format
npm install morgan 
 
配置
morgan-logging.js
const app = require('express')();
const morgan = require('morgan');
const { ecsFormat } = require('@elastic/ecs-morgan-format');
app.use(morgan(ecsFormat(/* options */)));  // 1
// ...
app.get('/', function (req, res) {
  res.send('hello, world!');
})
app.listen(3000); 
- 将 ECS 格式化程序传递给 morgan()。
 
配置 Filebeat
收集 ECS 格式化的日志的最佳方式是使用 Filebeat:
Filebeat 7.16+
filebeat.yml
filebeat.inputs:
- type: filestream   # 1
  paths: /path/to/logs.json
  parsers:
    - ndjson:
      overwrite_keys: true # 2
      add_error_key: true  # 3
      expand_keys: true    # 4
processors: # 5
  - add_host_metadata: ~
  - add_cloud_metadata: ~
  - add_docker_metadata: ~
  - add_kubernetes_metadata: ~ 
- 使用文件流输入从活动日志文件中读取行。
 - 如果发生冲突,解码的 JSON 对象的值将覆盖 Filebeat 通常添加的字段(type、source、offset 等)。
 - 如果发生 JSON 解组错误,Filebeat 将添加 “error.message” 和 “error.type: json” 键。
 - Filebeat 将递归地从解码的 JSON 中去掉点键,并将其扩展为分层对象结构。
 - 处理器可增强您的数据。请参阅 processor 以了解更多信息。
 
Filebeat < 7.16
filebeat.yml
filebeat.inputs:
- type: log
  paths: /path/to/logs.json
  json.keys_under_root: true
  json.overwrite_keys: true
  json.add_error_key: true
  json.expand_keys: true
processors:
- add_host_metadata: ~
- add_cloud_metadata: ~
- add_docker_metadata: ~
- add_kubernetes_metadata: ~ 
有关更多信息,请参阅 Filebeat 参考。
使用方法
morgan-logging.js
const app = require('express')();
const morgan = require('morgan');
const { ecsFormat } = require('@elastic/ecs-morgan-format');
app.use(morgan(ecsFormat(/* options */)));  // 1
app.get('/', function (req, res) {
  res.send('hello, world!');
})
app.get('/error', function (req, res, next) {
  next(new Error('boom'));
})
app.listen(3000) 
- 请参阅下面的可用选项。
 
运行上面的应用,并访问 http://localhost:3000。
npm install express 
$ pwd
/Users/liuxg/nodejs/nodejs-logs
$ ls
morgan-logging.js  pino-logging.js    winston-logging.js
$ node morgan-logging.js | jq . 

运行此脚本(完整示例在这里)并发出请求(通过 curl -i localhost:3000/)将产生类似于以上内容的日志输出。
Format 选项
你可以传递任何通常传递给 morgan() 的格式参数,日志 “message” 字段将使用指定的格式。默认为 combined。
const app = require('express')();
const morgan = require('morgan');
const { ecsFormat } = require('@elastic/ecs-morgan-format');
app.use(morgan(ecsFormat({ format: 'tiny' })));  // 1
// ... 
- 如果 “format” 是你使用的唯一选项,你可以将其作为 ecsFormat('tiny') 传递。
 
log.level
如果响应代码 >= 500,log.level 字段将为 “error”,否则为 “info”。例如,再次运行 examples/express.js,curl -i localhost:3000/error 将产生:
% node examples/express.js | jq .
{
  "@timestamp": "2021-01-18T17:52:12.810Z",
  "log.level": "error",
  "message": "::1 - - [18/Jan/2021:17:52:12 +0000] \"GET /error HTTP/1.1\" 500 1416 \"-\" \"curl/7.64.1\"",
  "http": {
    "response": {
      "status_code": 500,
  ... 
 
使用 APM 进行日志关联
此 ECS 日志格式化程序与 Elastic APM 集成。如果你的 Node 应用正在使用 Node.js Elastic APM Agent,则会将多个字段添加到日志记录中,以关联 APM 服务或跟踪和日志数据:
- 当前跟踪跨度时调用的日志语句(例如 logger.info(...))将包括跟踪字段 — trace.id、transaction.id。
 - 由 APM 代理确定或在 APM 代理上配置的多个服务标识符字段允许在 Kibana 中的服务和日志之间进行交叉链接 — service.name、service.version、service.environment、service.node.name。
 - event.dataset 在 Elastic Observability 应用中启用日志率异常检测。
 
例如,运行 examples/express-with-apm.js 和 curl -i localhost:3000/ 会产生包含以下内容的日志记录:
% node examples/express-with-apm.js | jq .
{
  // The same fields as before, plus:
  "service.name": "express-with-elastic-apm",
  "service.version": "1.1.0",
  "service.environment": "development",
  "event.dataset": "express-with-elastic-apm",
  "trace.id": "116d46f667a7600deed9c41fa015f7de",
  "transaction.id": "b84fb72d7bf42866"
} 
这些 ID 与 APM 代理报告的跟踪数据相匹配。
可以通过 apmIntegration: false 选项明确禁用与 Elastic APM 的集成,例如:
app.use(morgan(ecsFormat({ apmIntegration: false }))); 
 
参考
ecsFormat([options])
- options {type-object} 支持以下选项: 
  
- format {type-string} 格式名称(例如 combined)、格式函数(例如 morgan.combined)或格式字符串(例如 :method :url :status)。这用于格式化“message”字段。默认值 morgan.combined。
 - convertErr {type-boolean} 是否将记录的错误字段转换为 ECS 错误字段。默认值:true。
 - apmIntegration {type-boolean} 是否启用 APM 代理集成。默认值:true。
 - serviceName {type-string} “service.name”值。如果指定,则覆盖来自活动 APM 代理的任何值。
 - serviceVersion {type-string} “service.version”值。如果指定,则覆盖来自活动 APM 代理的任何值。
 - serviceEnvironment {type-string} “service.environment”值。如果指定,则将覆盖来自活动 APM 代理的任何值。
 - serviceNodeName {type-string} “service.node.name” 值。如果指定,则将覆盖来自活动 APM 代理的任何值。
 - eventDataset {type-string} “event.dataset” 值。如果指定,则将覆盖使用 ${serviceVersion} 的默认设置。
 
 
为 morgan 创建以 ECS 日志记录格式发出的格式化程序。










