Using pino api to add logs from different modules into file

887 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 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 obj = require('../logger')
const logger = obj.getLogger()
const expressLogger = expressPino({ logger });
const app = express()
    .use(expressLogger)
    .use('/',.........

bcd.ts

const obj = require('../logger')
const logger = obj.getLogger()
logger.warn("You are running with local configuration.");
0

There are 0 best solutions below