ELK(Elasticsearch+Logstash+Kibana)是日志分析的核心框架,需先完成基础部署:
elasticsearch.yml(设置cluster.name、node.name、network.host: localhost),并启动服务。kibana.yml(设置elasticsearch.hosts: ["localhost:9200"]),启动后通过http://localhost:5601访问。logstash.conf),定义输入、过滤、输出逻辑。为了让ELK更好解析,需将Node.js日志转为结构化格式(JSON)。推荐使用Winston日志库(支持多transport、日志分级):
const winston = require('winston');
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(), // 添加时间戳
winston.format.json() // 输出JSON格式
),
transports: [
new winston.transports.File({
filename: 'app.log',
maxsize: 100 * 1024 * 1024, // 100MB切割
level: 'info'
}),
new winston.transports.Console({
format: winston.format.simple() // 控制台输出简化格式
})
]
});
// 示例:记录带上下文的错误日志
logger.error('Database connection failed', {
errorCode: 'DB_503',
requestId: 'a1b2c3d4',
userId: 'user123'
});
结构化日志(如JSON)能让Logstash更易提取timestamp、level、message、errorCode等字段,提升后续分析效率。
Filebeat是ELK推荐的轻量级日志收集器(资源占用低),配置示例如下:
# filebeat.yml
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/node/*.log # Node.js日志路径
json.keys_under_root: true # 将JSON字段提升到顶层
json.add_error_key: true # 添加错误字段(如JSON解析失败)
output.logstash:
hosts: ["logstash:5044"] # 连接Logstash地址
compression_level: 3 # 启用gzip压缩(减少网络开销)
启动Filebeat:./bin/filebeat -e(-e表示输出到控制台,便于调试)。
若需更复杂的过滤(如提取IP、解析请求时间),可使用Logstash的grok插件。示例配置:
# logstash.conf
input {
beats {
port => 5044 # 监听Filebeat端口
}
}
filter {
if [fileset][module] == "node" { # 根据模块过滤(可选)
grok {
match => {
"message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{GREEDYDATA:message}"
}
}
date {
match => ["timestamp", "ISO8601"] # 解析时间戳为Elasticsearch格式
target => "@timestamp" # 替换默认的@timestamp字段
}
geoip {
source => "clientip" # 若日志中有IP,提取地理位置
target => "geoip"
}
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "nodejs-logs-%{+YYYY.MM.dd}" # 按日期分索引(便于管理)
}
stdout { codec => rubydebug } # 输出到控制台(调试用)
}
启动Logstash:./bin/logstash -f logstash.conf。
登录Kibana后,进入Stack Management > Index Patterns,点击“Create index pattern”,输入nodejs-logs-*(匹配Logstash输出的索引名),选择@timestamp作为时间字段,完成创建。
level: "error" and @timestamp >= now()-5mmethod: "GET" and path: "/api/v1/users" | stats percentile(response_time, 99)将常用的可视化组件添加到仪表盘(Dashboard > Create dashboard),可组合折线图、表格、饼图等,直观展示日志分析结果(如接口性能、错误趋势)。
logrotate工具避免日志文件过大(如每天切割、保留7天),配置示例:/var/log/node/*.log {
daily
missingok
rotate 7
compress
notifempty
create 640 root adm
}
indices.query.bool.max_clause_count(建议4096)、增加分片数(如3个主分片)。pipeline.workers为CPU核心数的2倍(提升处理并发)。log_viewer),限制索引访问权限(如仅允许读取nodejs-logs-*)。