1

I am using 'pino' package to create log object and using this object to display logs. However, I want to customize my log object by setting the object with a value I pass from outside. I need to use this object in all other files to print logs. After I set the log object using global variable, I am getting undefined in other files because I am importing the global variable at class level and then using that at method level. I do not want to import log in every method. Can someone help with some suggestions on how I can use global variables in all other files.

I have declared a global variable 'log'

global.d.ts

declare global {
  var log: any
}   

export { };

I am creating and returning log object here:

logger.ts

import pino from 'pino'
import pretty from 'pino-pretty'

export const setLog = (job_name:any)=>
{
  const streams = [
    { stream: pino.destination('myDetails.log') },
    { stream: pretty({
                colorize: true,
                sync: true,
                messageFormat: `{"job_name":${job_name}, "message":{msg}}`
              })
    }
  ]
  const logger = pino({level: 'info', timestamp: 
  pino.stdTimeFunctions.isoTime}, pino.multistream(streams))
  return logger;
}

I am passing job_name to logger and getting log object. I set this to global variable 'log'. After I do this, I use the global variable again and was able to print log line successfully.

intiateLoggerService.ts

import * as logger from 'logger';

export setLogObject()=>{
  global.log = logger.setLog(job_name);
  const log = global.log;
  log.info('global variable log is set');
}

I have a test function. I am using global log variable to print logs. But this is throwing error since log is assumed to be undefined here. This is because (as per my knowledge), "const log = global.log" gets executed when the project is started and during that time, log value was not set. I suppose same issue will occur when I use 'import log from ' as well. Can someone help with some suggestions.

index.ts

const log = global.log;

export testFunction1 = () => {
  log.info('testFunction starts here');
}

export testFunction2 = () => {
  log.info('testFunction starts here');
}

My final output is

global variable log is set
Cannot read properties of undefined (reading 'info')
Rahul Sharma
  • 5,562
  • 4
  • 24
  • 48
Pavan Kumar
  • 129
  • 7

0 Answers0