插件窝 干货文章 Linux下Node.js日志如何管理

Linux下Node.js日志如何管理

日志 log Winston Node 391    来源:    2025-05-07

Linux下Node.js日志管理方案

作为IT工程师,我为您提供几种在Linux环境下管理Node.js日志的有效方案:

1. 基础日志方案

使用内置console模块

console.log('Info message');
console.error('Error message');

使用Winston日志库

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' })
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

2. 高级日志管理方案

使用PM2的日志管理

# 启动应用并记录日志
pm2 start app.js --log-date-format "YYYY-MM-DD HH:mm Z" --log /var/log/node-app.log

# 日志轮转
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30

使用Bunyan结构化日志

const bunyan = require('bunyan');
const log = bunyan.createLogger({
  name: 'myapp',
  streams: [
    {
      level: 'info',
      path: '/var/log/myapp-info.log'
    },
    {
      level: 'error',
      path: '/var/log/myapp-error.log'
    }
  ]
});

3. 系统级日志管理

配置logrotate

创建/etc/logrotate.d/node-app文件:

/var/log/node-app.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        pm2 reloadLogs > /dev/null
    endscript
}

使用systemd journal

# 查看日志
journalctl -u your-node-service -f -n 100

# 按优先级过滤
journalctl -u your-node-service -p err

4. 日志集中化方案

使用ELK Stack (Elasticsearch, Logstash, Kibana)

  1. 配置Logstash输入:
input {
  file {
    path => "/var/log/node-app.log"
    type => "nodejs"
  }
}

使用Fluentd

<source>
  @type tail
  path /var/log/node-app.log
  pos_file /var/log/node-app.log.pos
  tag node.app
  format none
</source>

5. 最佳实践建议

  1. 日志分级:合理使用error、warn、info、debug等级别
  2. 结构化日志:使用JSON格式便于后续处理
  3. 敏感信息过滤:避免记录密码、密钥等敏感信息
  4. 性能考虑:异步日志记录避免阻塞主线程
  5. 监控告警:对ERROR级别日志设置告警

您可以根据项目规模、团队需求选择合适的日志管理方案。对于生产环境,建议至少实现日志轮转和集中化查看功能。