Writing every log.info content to a text file

Viewed 31

I am using Pino and Pino pretty packages for displaying loggers. I would like to write all log.info contents (called from multiple js files in the same project) into a common text file

logger.ts
import pinoCaller from 'pino-caller'
import pino from 'pino'
const job_name="job123"
const pinoPretty = pino(
    {
      prettyPrint: {
        messageFormat: `{"job_name":${job_name}, "message":{msg}}`,        
      },
    })
export log=pinoCaller(pinoPretty)

Is there anyway I can write all log.info content from multiple files to a common text file.

lets say I have following files:

file1.ts
import {log} from 'logger'
const calculatesum = (a:any,b:any)=>{
log.info('**********')
log.info('sum begins')
const sum=a+b;
log.info('sum is '+sum)
log.info('sum ends')
}
file2.ts
import {log} from 'logger'
const calculateproduct = (a:any,b:any)=>{
log.info('product begins')
const product=a*b;
log.info('product is '+product)
log.info('product ends')
log.info('**********')
}

output of text file should look like below:

***************
sum begins
sum is x
sum ends
product begins
product is y
product ends
***************
1 Answers

If you're using Pino v7.x or later, you can make use of Pino transports.

const pinoPretty = pino({
  prettyPrint: {
      messageFormat: `{"job_name":${job_name}, "message":{msg}}`,        
  },
  transport: {
    targets: [
      { level: 'info', target: 'pino/file', options: { destination: '/path/to/store/logs', mkdir: true } },
      { target: 'pino-pretty', options: { destination: '/dev/null' }
    ]
  }
})

Alternatively you can use pino-tee. An example of how to do it:

const pino = require('pino')

const pinoTee = pino.transport({
  target: 'pino-tee',
  options: {
    filters: {
      info: 'info.log'
    }
  }
})
Related