pm2日誌記錄和日誌分割
阿新 • • 發佈:2018-03-02
tle RKE inter midnight base ber -s 介紹 進程
pm2日誌記錄和日誌分割
pm2介紹
pm2是nodejs進程管理工具,現在基本是node生產服務器的標準選擇,可以幫助我們實現node多進程服務,開啟的多個實例自動實現負載均衡。 最重要的是保證node單進程不會因為錯誤退出,作為守護進程保證nodejs服務不宕機。 總體來說就是有性能監控、自動重啟、負載均衡的作用。
pm2-logrotate介紹
pm2本身是可以輸出日誌文件的,默認的文件路徑:
error log path │ /home/username/.pm2/logs/app-error-0.log out log path │ /home/username/.pm2/logs/app-out-0.log
但是pm2的日誌文件不能自動分割,這會導致一個文件不斷變大,不但影響性能,查看這些日誌也會帶來麻煩。所以需要pm2-logrotate
來實現自動分割日誌。
安裝pm2-logrotate
pm2 install pm2-logrotate
,是用pm2命令,不是npm命令
pm2-logrotate配置
- ``max_size` (默認 10M): 最大為多少時進行分割,例如: 10G, 10M, 10K
- ``retain` (Defaults to all): 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.
compress
(默認 false): 是否壓縮日誌dateFormat
(默認 YYYY-MM-DD_HH-mm-ss) : 日誌格式rotateModule
(Defaults to true) : Rotate the log of pm2‘s module like other appsworkerInterval
(Defaults to 30 in secs) : You can control at which interval the worker is checking the log‘s size (minimum is 1)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 :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.
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ 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)
可以嘗試使用pm2 set pm2-logrotate:max_size 1K (1KB)
設置日誌文件最大為1KB 代碼中console.log
的內容會輸出到 /home/username/.pm2/logs/app-out-0.log
, 大小達到1KB就會自動生成 app-out-0__2018-01-25_16-58-16.log
這種格式的日誌文件。 在/home/username/.pm2/logs/
(默認路徑,可以配置)路徑下還有
app-error-0.log
pm2-logrotate-out-1.log
pm2-logrotate-error-1.log
幾個文件,app-out-0.log
文件記錄的就是console.log
輸出,app-error-0.log
記錄的是錯誤輸出,pm2-logrotate-out-1.log
和pm2-logrotate-error-1.log
分別記錄的是分割的日誌文件,是這樣的內容:
"/home/username/.pm2/pm2__2018-01-25_16-57-16.log" has been created
"/home/username/.pm2/logs/app-out-0__2018-01-25_16-58-16.log" has been created
"/home/username/.pm2/logs/app-out-0__2018-01-25_16-58-46.log" has been created
pm2日誌記錄和日誌分割