node.jslog-rotationpinojs

How to rotate log files that generate with pino-multi-stream?


I am using pino-multi-stream npm package in my node.js project as below:

const fs = require('fs');
const pino = require('pino');
const multistream = require('pino-multi-stream').multistream;
const path = require('path');

const logDirectory = path.join(__dirname, '..', 'logs');
const streams = [
  { stream: fs.createWriteStream(`${logDirectory}/info.log`) },
  { level: 'info', stream: fs.createWriteStream(`${logDirectory}/info.log`) },
  { level: 'debug', stream: fs.createWriteStream(`${logDirectory}/debug.log`) },
  { level: 'warn', stream: fs.createWriteStream(`${logDirectory}/warn.log`) },
  { level: 'error', stream: fs.createWriteStream(`${logDirectory}/error.log`) },
  { level: 'fatal', stream: fs.createWriteStream(`${logDirectory}/fatal.log`) }
];

const logger = pino({ level: 'debug' }, multistream(streams));
export { pino, logger };

And using logger like:

logger.info(`Ready on localhost:${port}`);
logger.error('error message');
logger.warn('warning message');
...

Now I have multi log files into logs directory in my project.

My question is :

How to rotate this files (such as "daily" rotation, with npm packages like "file-stream-rotator")?


Solution

  • Simply pass streams that file-stream-rotator gets you to the pino-multi-stream.

    { level: 'info', stream: fs.createWriteStream(`${logDirectory}/info.log`) },
    

    to

    { level: 'info', stream: require('file-stream-rotator').getStream({filename:`${logDirectory}/info.log`, frequency:"daily"}) },