Nodejs Merging log with PM2 and Winston

10.2k views Asked by At

I want to log all the information only in one file. I am using pm2 "0.12.1" and "winston": "0.8.3".

Here is my code of winston

var winston = require('winston');

var customLoggerLevels = {
  levels: {
    trace: 0,
    debug: 1,
    info: 2,
    warn: 3,
    error: 4
  },
  colors: {
    trace: 'blue',
    debug: 'green',
    info: 'grey',
    warn: 'yellow',
    error: 'red'
  }
};

var logger = new (winston.Logger)({
  levels: customLoggerLevels.levels
});

and a piece of my ecosystem.json

 "apps" : [
    {
      "name"      : "myapp",
      "script"    : "server.js",
      "instances"  : "1",
      "err_file"    : "myapp.log",
      "out_file"    : "myapp.log",
      "env": {
        "NODE_ENV": "development",
        "PORT": 4000
      },
      "env_production" : {
        "NODE_ENV": "production",
        "PORT": 4000
      }
    }
  ]

This is not working for me. I don't understand why pm2 still creates two files one for out and one for error. Also I want to know if it is possible to put the file in another directory in production.

Thank you

1

There are 1 answers

2
soyuka On BEST ANSWER

You can specify a file path in the out_file and error_file keys. By default, pm2 redirect the stdout output to a different file than the stderr output. If you want to have only one log file, simply use the same path for both output.

Your ecosystem.json would look like this:

"apps" : [
    {
      "name"      : "myapp",
      "script"    : "server.js",
      "instances"  : "1",
      "error_file"    : "/var/log/myapp.log",
      "out_file"    : "/var/log/myapp.log",
      "env": {
        "NODE_ENV": "development",
        "PORT": 4000
      },
      "env_production" : {
        "NODE_ENV": "production",
        "PORT": 4000
      }
    }
  ]

There is also an option that merge the logs of every instances (it's not merging out/err). To use it specify merge_logs: true. It'll also allow you to get rid of the pm2 id in the log filename.