PM2 启动 Next.js 项目,不记录 console 日志的问题

12 阅读1分钟

使用 PM2 启动项目后,发现 PM2 不记录 Next.js 项目中使用 console.log() 输出的内容。

具体现象是,使用命令 pm2 logs app-name 查看日志时总是为空,但是用 pm2 logs 查看所有服务的日志却能够看到 app-name 的 log 输出。

这是我的 PM2 ecosystem.config.js 配置文件:

/**
 * @type {import('pm2').StartOptions}
 */
module.exports = {
  apps: [
    {
      name: 'app-name',
      // script: './dist/main.js',
      script: 'npm', // 使用 npm 作为启动脚本
      args: 'run start', // 传递给 npm 的参数,这里是 start
      interpreter: 'none', // 不需要额外的解释器 因为 npm、next 本身是一个可执行命令,不需要额外的解释器
      exec_mode: 'cluster',
      instances: 1,
      merge_logs: true, // 让不同进程的日志写进同一个日志文件中
      autorestart: true,
    },
  ],
};

经过多次调试后发现,是启动命令的问题,让 PM2 去执行 npm run start 时会导致这个问题的出现。

改成使用 next start 命令启动即可解决:

/**
 * @type {import('pm2').StartOptions}
 */
module.exports = {
  apps: [
    {
      name: 'app-name',
      // script: './dist/main.js',
      script: 'next', // 使用 next 作为启动脚本
      args: 'start --port 3000', // 传递给 next 的参数,这里是 start
      // 注意!不要使用npm作为启动脚本, 这样会导致pm2记录不到next.js项目console.log的日志, 建议直接使用 next 启动
      // script: 'npm', // 使用 npm 作为启动脚本
      // args: 'run start', // 传递给 npm 的参数,这里是 start
      interpreter: 'none', // 不需要额外的解释器 因为 npm、next 本身是一个可执行命令,不需要额外的解释器
      exec_mode: 'cluster',
      instances: 1,
      merge_logs: true, // 让不同进程的日志写进同一个日志文件中
      autorestart: true,
    },
  ],
};