插件窝 干货文章 如何快速筛选Node.js关键日志信息

如何快速筛选Node.js关键日志信息

日志 使用 筛选 高亮 429    来源:    2025-05-05

快速筛选Node.js关键日志信息的方法

在Node.js应用中,随着应用规模扩大,日志量会急剧增加。以下是几种高效筛选关键日志信息的方法:

1. 使用日志级别过滤

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info', // 只记录info及以上级别
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'error.log', level: 'error' }) // 单独存储错误日志
  ]
});

2. 使用grep命令快速筛选

# 查找错误日志
grep -i "error" app.log

# 查找特定请求ID的日志
grep "reqId:12345" app.log

# 查找过去5分钟内的日志
grep "$(date -d '5 minutes ago' '+%Y-%m-%d %H:%M')" app.log

3. 使用日志分析工具

  • Pino + pino-pretty: 结构化JSON日志与美化输出

    node app.js | pino-pretty -t
    
  • ELK Stack (Elasticsearch, Logstash, Kibana): 强大的日志分析平台

  • Splunk: 企业级日志管理

4. 结构化日志输出

// 使用JSON格式输出日志
logger.info({
  message: 'User logged in',
  userId: 123,
  ip: '192.168.1.1',
  timestamp: new Date().toISOString()
});

5. 关键字段高亮显示

# 使用grep高亮关键词
grep --color=auto -E "error|warn|critical" app.log

6. 使用日志聚合工具

  • Loki: Grafana的日志聚合系统
  • Fluentd: 开源数据收集器
  • Loggly: SaaS日志管理服务

7. 自定义日志筛选脚本

// 简单的Node.js日志筛选脚本
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: fs.createReadStream('app.log'),
  output: process.stdout,
  terminal: false
});

rl.on('line', (line) => {
  if (line.includes('ERROR') || line.includes('WARN')) {
    console.log(line);
  }
});

最佳实践建议

  1. 在开发环境使用详细日志,生产环境只记录关键信息
  2. 为日志添加请求ID或事务ID以便追踪
  3. 定期归档和清理旧日志
  4. 对敏感信息进行脱敏处理
  5. 设置日志文件大小限制和轮转策略

通过以上方法,您可以有效地从海量日志中快速定位关键信息,提高问题排查效率。