首页 > 解决方案 > 为作为 systemd 服务运行的 Nodejs 应用程序设置日志优先级

问题描述

我有一个作为 systemd 服务运行的应用程序。

可以使用我想要的 journalctl 访问日志,但是尽管节点记录 console.error > stderr,但似乎无法使用 -p(riority) 过滤器从 console.log 条目中识别 console.error。

似乎所有日志都没有优先级发送:

journalctl -fu my-app.* -p 3

尽管存在错误日志,但尝试显示错误日志 (p=3) 会导致没有日志。

如何配置 nodejs 以输出具有优先级的日志,以便我可以使用 journalctl 过滤错误和正常日志文件?

标签: node.jssystemd

解决方案


<priority>通过在所有日志前面加上这个来解决:

function jclogs(){
  
  var levels = {
    alert   : 1,
    error   : 3,
    warn    : 4,
    info    : 6,
    log     : 7
  }
  
  for(var level in levels){
    const pri = levels[level];
    console[level] = function(...args) {
      var line = [`<${pri}>`];
      args.map(function(arg){
        if(typeof arg != 'string') try {arg = JSON.stringify(arg)} 
        catch(e){};
        line.push(arg); 
      })
      process.stdout.write(`${line.join(' ')}\n`); 
    }
  }
}

它还尝试对任何数据进行字符串化。


推荐阅读