在Debian上分割Node.js应用程序的日志,可以使用多种方法。以下是几种常见的方法:
pm2 进行日志管理pm2 是一个流行的Node.js进程管理器,它提供了强大的日志管理功能。
安装 pm2:
npm install pm2 -g 启动你的Node.js应用程序:
pm2 start app.js --name my-app 配置日志分割: pm2 默认会自动分割日志文件。你可以通过配置文件进一步自定义日志分割策略。
创建一个 ecosystem.config.js 文件:
module.exports = { apps: [{ name: 'my-app', script: 'app.js', instances: 'max', exec_mode: 'cluster', autorestart: true, watch: false, max_memory_restart: '1G', log_date_format: 'YYYY-MM-DD HH:mm Z', out_file: './logs/out.log', error_file: './logs/err.log', merge_logs: true, log_file: './logs/node.log', time: true, log_rotation: { interval: '1d', line_limit: 200000, size_limit: 10000000 } }] }; 启动应用程序:
pm2 start ecosystem.config.js logrotatelogrotate 是一个系统工具,用于管理日志文件的轮转和压缩。
安装 logrotate(如果尚未安装):
sudo apt-get install logrotate 创建一个 logrotate 配置文件: 在 /etc/logrotate.d/ 目录下创建一个新的配置文件,例如 nodejs:
sudo nano /etc/logrotate.d/nodejs 添加以下内容:
/path/to/your/nodejs/logs/*.log { daily missingok rotate 7 compress notifempty create 0640 root adm } 测试配置:
sudo logrotate -f /etc/logrotate.d/nodejs winston 和 winston-daily-rotate-filewinston 是一个流行的Node.js日志库,结合 winston-daily-rotate-file 可以实现日志的每日分割。
安装 winston 和 winston-daily-rotate-file:
npm install winston winston-daily-rotate-file 配置 winston: 在你的Node.js应用程序中配置 winston:
const winston = require('winston'); const DailyRotateFile = require('winston-daily-rotate-file'); const transport = new DailyRotateFile({ filename: 'application-%DATE%.log', datePattern: 'YYYY-MM-DD-HH', zippedArchive: true, maxSize: '20m', maxFiles: '14d' }); const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ transport ] }); logger.info('Hello, world!'); 通过以上方法,你可以在Debian上有效地分割和管理Node.js应用程序的日志。选择适合你需求的方法进行配置即可。