node.jssystemd

Setting log priority for Nodejs app running as systemd service


I have an application which is running as a systemd service.

Logs can be accessed using journalctl which is what I want, however despite the fact that node logs console.error > stderr, it does not seem possible to identify console.error from console.log entries using the -p(riority) filter.

It seems that all logs are sent without a priority:

journalctl -fu my-app.* -p 3

Attempting to show error logs ( p=3) results in no logs, despite the fact that there are error logs.

How can I go about configuring nodejs to output it's logs with a priority level so that I can filter error and normal log files using journalctl ?


Solution

  • You can get systemd to set the correct priority by by prepending the <priority> to all logs like this:

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

    This also attempts to stringify any data.

    Prefixing the priority like this works because systemd will read the priority from the message if you prefix the message with the priority like this: "<priority> rest of message"

    Docs: https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html#SyslogLevelPrefix=