node.jsloggingpinojs

Logging to STDOUT and a file with node/pino


I am sharing this as I struggled to get a pino logger to write to both STDOUT and a log file:

const dest = new stream.PassThrough();
dest.pipe(process.stdout);
dest.pipe(fs.createWriteStream('/logs/file.log', { flags: 'a' }));
const logger = pino({ level: 'info' }, dest);

As this appears very low level, I wonder if this is the right way to do this.


Solution

  • A bit late but pino-multi-stream may be what you want. I followed this section here and it works for me in TypeScript for my purpose. You could try something like this:

    const fs = require('fs');
    const pinoms = require('pino-multi-stream')
    
    const streams = [
      { stream: process.stdout },
      { stream: fs.createWriteStream('/logs/file.log', { flags: 'a' }) },
    ]
    
    const logger = pino({ level: 'info' }, pinoms.multistream(streams));