Pino logger custom destinations based on log level and logging on nodeJS console

3.1k Views Asked by At

Im having a hard time logging on Stdout and logging in file. Is there a way to log on stdout based on log level and at the same time log in file?

As of now, my code is currently logging on text file base on their current level. Example if the log is info, it will go to info.log, if error, it will go to error.log, however i want is both on text file and on nodejs console. but i cant achieve that.

Here is my current code:

const levels = {
  error: 50,
  info: 20,
  debug: 10,
};

const streams = Object.keys(levels).map((level) => {
  return  {
    level: level,
    stream: fs.createWriteStream(`${__dirname}/app-${level}.log`, {
      flags: "a",
    }),
  };
});

module.exports = pinoLogger(
  {
    level: "info",
    customLevels: levels,
    useOnlyCustomLevels: true,
    formatters: {
      level: (label) => {
        return { level: label };
      },
    },
  },
  pinoms.multistream(streams, {
    levels,
    dedupe: true,
  })
);

Testing code:

pinoLogger.error("Test 1");

This testing code is going to "app-error.log" w/c correct, however like what i have said, i want it to nodejs console too. Thankyou :)

1

There are 1 best solutions below

0
On

Thanks for your code,really benefit for me. Try add transport part as follow hope help you.

module.exports = pinoLogger(
  {
    level: "info",
    customLevels: levels,
    useOnlyCustomLevels: true,
    formatters: {
      level: (label) => {
        return { level: label };
      },
    },
    transport: {
      target: 'pino-pretty',
      options: {
        colorize: true,
        translateTime: 'SYS:yyyy-mm-dd hh:MM:ss',
        ignore: 'pid',
      },
    },
  },
  pinoms.multistream(streams, {
    levels,
    dedupe: true,
  })
);