let winston.info() print state of object

Viewed 13

I have a collection of instances, for example "Bots". And I want that when each bot calls logger.info('some text) also the internal state of the bot will be printed as part of the log.

logger = winston.createLogger({
    format: format.combine(
      format.timestamp({format: 'MM-DD HH:mm'}),
      format.label('label',{message:false}),
      format.printf(({timestamp, level, message, bot, ...rest})=>{
        // print that know about internal bot state
        return `${timestamp} ${level}[bot.mode]  ${bot.name}: ${message}`
      }),
    ),
    transports: [
        new winston.transports.Console({ level: "silly", format: consoleFormat })
    ],
  });
class Bot{
 constructor(name){
  this.mode = 'wet';
  this.name = name;
 }
 wetMode(){ this.mode = 'wet'}
 dryMode(){ this.mode = 'dry' }
 talk(text){
   logger.info(text) 
 }
}

bot1 = new Bot('Game')

// So let say if I call 
bot1.talk('foo')
// I want print look like:  `21-09 22:00 info[wet]  Game: foo`
1 Answers

I found a solution, add a custom format that runs before and normalize the instance. and create a new logger.child and bring it this

logger = winston.createLogger({
    format: format.combine(
        format(function bot(info, opts){
         const { bot} = info;
         delete info.bot;
         if(bot) info.bot ={
            mode: bot.dryMode?'dry':'wet',
            name: bot.chatGroup?.name ?? bot.setting.name
         }    
        return info;
     })
     format.timestamp({format: 'MM-DD HH:mm'}),
     format.label('label',{message:false}),
     format.printf(({timestamp, level, message, bot, ...rest})=>{
       // print that know about internal bot state
       return `${timestamp} ${level}[bot.mode]  ${bot.name}: ${message}`
     }),
    ),
    transports: [
        new winston.transports.Console({ level: "silly", format: consoleFormat })
    ],
  });
class Bot{
 constructor(name){
  this.mode = 'wet';
  this.name = name;
  this.logger= logger.child({bot:this})
 }
 wetMode(){ this.mode = 'wet'}
 dryMode(){ this.mode = 'dry' }
 talk(text){
   this.logger.info(text) 
 }
}

Related