ubuntu

Node.js日志在Ubuntu如何做性能分析

小樊
51
2025-09-26 20:11:30
栏目: 编程语言

1. 启用结构化日志记录
结构化日志(如JSON格式)是性能分析的基础,便于后续用工具解析和聚合数据。推荐使用WinstonPino这类高级日志库,它们支持多传输(文件、控制台)、日志级别(info/warn/error)和格式化。例如,用Winston配置JSON日志:

const winston = require('winston');
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(), // 结构化输出
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});
logger.info('Request received', { method: 'GET', path: '/api', latency: 120 }); // 包含性能指标

2. 记录关键性能指标
在代码中埋点记录响应时间、内存使用、CPU占用等核心指标,为分析提供数据源。例如:

// 记录请求响应时间(毫秒)
const start = process.hrtime();
app.get('/api', (req, res) => {
  // 业务逻辑...
  const diff = process.hrtime(start);
  const latency = (diff[0] * 1e9 + diff[1]) / 1e6;
  logger.info('Request completed', { method: req.method, path: req.path, latency });
});

// 定期记录内存和CPU使用率
setInterval(() => {
  const memory = process.memoryUsage();
  const cpu = process.cpuUsage();
  logger.info('System metrics', { 
    memoryUsage: `${memory.heapUsed / 1024 / 1024}MB`, 
    cpuUsage: `${(cpu.user / 1e6).toFixed(2)}ms` 
  });
}, 5000); // 每5秒记录一次

3. 使用命令行工具快速分析
Ubuntu的命令行工具可快速定位性能问题,适合日常排查:

4. 利用日志管理工具深度分析
对于大规模或分布式系统,使用ELK Stack(Elasticsearch+Logstash+Kibana)或Graylog等工具,实现日志的集中存储、可视化和高级分析:

5. 日志轮转避免文件过大
使用Logrotate工具定期分割、压缩日志文件,防止磁盘空间耗尽。创建/etc/logrotate.d/nodejs配置文件:

/path/to/your/nodejs/*.log {
  daily # 每天轮转
  missingok # 文件不存在不报错
  rotate 7 # 保留7天
  compress # 压缩旧日志
  notifempty # 空文件不轮转
  create 0640 root adm # 新日志权限
}

6. 高级性能分析工具

0
看了该问题的人还看了