温馨提示×

Node.js 在 Linux 中如何进行日志管理

小樊
45
2025-11-24 06:09:18
栏目: 编程语言

在 Linux 系统中,Node.js 应用程序的日志管理可以通过以下几种方式进行:

  1. 使用内置的 console 模块:Node.js 提供了一个内置的 console 模块,可以用于在控制台输出日志。这对于调试和开发过程中查看日志非常有用。例如:
console.log('This is a log message');
console.error('This is an error message');
  1. 使用日志库:有许多第三方日志库可以帮助您更好地管理日志,例如 winstonbunyan。这些库提供了更多的功能,如日志级别、日志格式化和日志轮转等。
  • 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' })
  ]
});

logger.info('This is an info message');
logger.error('This is an error message');
  • Bunyan 示例:
const bunyan = require('bunyan');

const logger = bunyan.createLogger({
  name: 'my-app',
  streams: [
    { level: 'info', stream: process.stdout },
    { level: 'error', path: 'error.log' },
    { level: 'info', path: 'combined.log' }
  ]
});

logger.info('This is an info message');
logger.error('This is an error message');
  1. 日志轮转:当日志文件变得过大时,可以使用日志轮转工具来自动分割和压缩日志文件。在 Linux 中,常用的日志轮转工具有 logrotatepm2
  • logrotate 示例:在 /etc/logrotate.d/ 目录下创建一个配置文件,例如 my-node-app
/path/to/your/node/app/*.log {
  daily
  rotate 7
  compress
  missingok
  notifempty
  create 0640 root root
}

这将每天轮转日志文件,并保留最近 7 天的日志。

  • pm2 示例:使用 pm2 管理 Node.js 应用程序,并启用日志轮转:
npm install pm2 -g
pm2 start app.js --name my-node-app
pm2 set pm2:logrotate:max_size 10M
pm2 set pm2:logrotate:retain 7

这将限制日志文件大小为 10MB,并保留最近 7 天的日志。

通过这些方法,您可以在 Linux 系统中有效地管理 Node.js 应用程序的日志。

0