PM2 allows you to manage logs easily. You can display all application logs in real-time, flush them, and reload them. There are also different ways to configure how PM2 will handle your logs (separated in different files, merged, with timestamp...) without modifying anything in your code.

实时显示日志

实时查看所有日志或指定进程日志:

$ pm2 logs
$ pm2 logs big-api

刷新日志

PM2的日志管理将清空当前所有应用日志:

$ pm2 flush # Clear all the logs

或者可以安装日志轮记录器来操作日志轮循.

重载所有日志

Reloading logs is specially usefull for Logrotate or any other rotating log system. You can reload logs by sending SIGUSR2 to the PM2 process.

可以通过命令行重载所有日志:

$ pm2 reloadLogs

日志配置

CLI

示例:

$ pm2 start echo.js --merge-logs --log-date-format="YYYY-MM-DD HH:mm Z"

选项:

  • --merge-logs do not postfix log file with process id
  • --log-date-format 格式化时间戳的日志前缀
  • -l --log [path] 指定整个日志文件 (包含错误和输出日志)
  • -o --output 制定输出日志文件
  • -e --error 指定错误日志文件

JSON 方式

{
  "script"          : "echo.js",
  "error_file"        : "err.log",
  "out_file"        : "out.log",
  "merge_logs"      : true,
  "log_date_format" : "YYYY-MM-DD HH:mm Z"
}

注意: To merge all logs into the same file set the same value for error_file, out_file.

设置了一个本机 logrotate

$ sudo pm2 logrotate -u user

这将写一个基础日志轮循配置到 /etc/logrotate.d/pm2-user ,如下:

/home/user/.pm2/pm2.log /home/user/.pm2/logs/*.log {
        rotate 12
        weekly
        missingok
        notifempty
        compress
        delaycompress
        create 0640 user user
}

pm2-logrotate 模块

pm2-logrotate 自动轮训PM2日志和应用管理

$ pm2 install pm2-logrotate