pm2 日志管理及使用 pm2-logrotate 进行日志分割
pm2 自带日志管理功能,日志模块默认是每一个服务进程都分配两个默认的日志文件,这两个日志文件存放于/root/.pm2/logs中。
一、日志管理
启动项目后,可以通过命令 $ pm2 logs 查看,此时屏幕上会同时输出 error log 和实时 log, 同时会打印出日志文件的路径。
$ pm2 logs
同时我们也可以使用 tail -f 查看指定的文件的日志,如下:
$ tail -f /root/.pm2/logs/main-out.log
二、日志切割
1、安装 pm2-logrotate
但是pm2自带的日志功能是不支持自动分割的,这就会导致日志文件会越来越大,可以使用 pm2-logrotate 插件来解决这个问题。其安装也是非常简单,如下
$ pm2 install pm2-logrotate
安装完成后就可以通过 pm2 list 命令查看,此时模块列表中已经有了 pm2-logrotate 模块。此时通过 pm2 conf pm2-logratate 可以查看详细的配置,如下:
$ pm2 conf pm2-logratate
pm2-logrotate 具体配置说明:
max_size (Defaults to 10M): When a file size becomes higher than this value it will rotate it (its possible that the worker check the file after it actually pass the limit) . You can specify the unit at then end: 10G, 10M, 10K
配置项默认是 10MB,并不意味着切割出来的日志文件大小一定就是 10MB,而是检查时发现日志文件大小达到 max_size,则触发日志切割。
retain (Defaults to 30 file logs): This number is the number of rotated logs that are keep at any one time, it means that if you have retain = 7 you will have at most 7 rotated logs and your current one.
这个数字是在任何一个时间保留已分割的日志的数量,这意味着如果您保留7个,那么您将最多有7个已分割日志和您当前的一个
compress (Defaults to false): Enable compression via gzip for all rotated logs
对所有已分割的日志启用 gzip 压缩
dateFormat (Defaults to YYYY-MM-DD_HH-mm-ss) : Format of the data used the name the file of log
文件名格式化的规则
rotateModule (Defaults to true) : Rotate the log of pm2's module like other apps
像其他应用程序一样分割 pm2模块的日志
workerInterval (Defaults to 30 in secs) : You can control at which interval the worker is checking the log's size (minimum is 1)
您可以控制工作线程检查日志大小的间隔(最小值为1)单位为秒(控制模块检查log日志大小的循环时间,默认30s检查一次)
rotateInterval (Defaults to 0 0 * * * everyday at midnight): This cron is used to a force rotate when executed. We are using node-schedule to schedule cron, so all valid cron for node-schedule is valid cron for this option. Cron style :
多久备份一次
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
TZ (Defaults to system time): This is the standard tz database timezone used to offset the log file saved. For instance, a value of Etc/GMT+1, with an hourly log, will save a file at hour 14 GMT with hour 13(GMT+1) in the log name.
时区(默认为系统时区)
2、设置
# pm2 set pm2-logrotate:<param> <value>
例如:
# pm2 set pm2-logrotate:max_size 1K (1KB)
# pm2 set pm2-logrotate:compress true (compress logs when rotated)
# pm2 set pm2-logrotate:rotateInterval '*/1 * * * *' (force rotate every minute)