首页 > 解决方案 > 我们如何使用 node js 中的 pm2 api 显示 pm2 应用程序的最新日志?

问题描述

我正在尝试制作一个 api,我们可以在其中获取 pm2 应用程序的最新日志,但我很难做到这一点。

//Helper function to get the logs
async function getLogs(id, out, numLines){
  for (const elem of currentInfo){
    //Finds the appropriate process
    if (elem.pm_id == id){
      //Gets the appropiate file
      let file = out == "true" ? elem.pm2_env.pm_out_log_path : elem.pm2_env.pm_err_log_path;
      
      //Uses an external library to get the proper lines
      let logs = await readLastLines.read(file, numLines);

      return {logs: logs}
    }
  }
  return {logs: undefined};
}

//Log route, sends the proper part of the necessary log file.
//Param 1: id - id of the process in the pm2 daemon
//Param 2: out - true if requesting the stdout logs, otherwise gets the stderr logs
//Param 3: numLines - number of lines of the log file requested (gets the most recent lines)
app.get('/logs/:id/:out/:numLines', async function(req, res){
  let temp = await getLogs(req.params.id, req.params.out, req.params.numLines)
  res.send(temp);
})

标签: javascriptnode.jspm2

解决方案


推荐阅读