Using pino api to add logs from different modules into 1 file

1.2k Views Asked by At

I am working on nodejs project. How to add Pino logger on different modules and add logs into a a file. I can add logs on console though. Can you please advise on adding all logs in one log file using pino.

logger.ts

const pino = require('pino')
const childProcess = require('child_process');
const stream = require('stream');
 
// Environment variables
const cwd = process.cwd();
const {env} = process;
const logPath = `${cwd}/log`;
console.log(`-------${logPath}`)
export function getLogger( verbosity: string) {
    // Create a stream where the logs will be written
    const logThrough = new stream.PassThrough();
    //const log = pino({name: 'project'}, logThrough);
    
    // Log to file
    const child = childProcess.spawn(process.execPath, [
        require.resolve('pino-tee'),`${logPath}/warn.log`
    ], {cwd, env});
    
    logThrough.pipe(child.stdin);
    return pino({ level: verbosity || process.env.LOG_LEVEL || 'info' }).child({logThrough})
}

abc.ts

const expressPino = require('express-pino-logger')
const obj = require('../logger')
const logger = obj.getLogger()
const expressLogger = expressPino({ logger });
const app = express()
    .use(expressLogger)
    .use('/',.........

not working

1

There are 1 best solutions below

1
On

According to the documentation you can do this using:

// destination param may be in first position when no options:
const fileLogger = require('pino')( pino.destination('/log/path'))

or even simpler:

// automatic wrapping in pino.destination
const fileLogger = require('pino')('/log/path')