Search code examples
javascriptnode.jswinston

Is it possible to segregate logger with name?


currently if I run logger.debug('message') I get output like this

{"message":"message","level":"debug"}

Is it possible to do something on creation of logger, so that the message will look more like this?

{"message":"message","level":"debug","name":"someModule"}

I would like in the end, for each module to customise its own logger, so it is clear form which module the logging came

In case winston logger has no function of this own, can you recommend one logging library that has?


Solution

  • You might use custom-logger

    There you can define something like:

    var log = require('custom-logger').config({ format: "%message% %level%[%timestamp%]: %name%" });
    

    also, something more complex like:

    log.new({
        alert: { level: 3, color: 'red', event: 'alert', format: '!!!!!%event% : %message% !!!!!' name: '%name%' }
    });
    

    And very simple like:

    log.info("I see %d %s!", 3, "bananas"); 
    

    Getting the output: Outputs "I see 3 bananas!"

    For your specific question, you might add this to your code:

    log.new({
       debug: { message: "This is the message" , level :"debug", name: "Your module name"}
    });
    

    To use the standard provided by the library:

    log.new({
           fatal: { message: "THIS IS THE END!" , level :"fatal", name: "Your module name"}
        });
    

    In case you want to define your own colors to have a better overview:

    log.info().config({ color: 'cyan' }); //This should be declared as global
    log.info('Hello World!');
    

    Also, you can assign

    try {
      eval('alert("Hello world)');
    }
    catch(error) {
      console.error(error);
      log.new({
         error: { message: error, level :"error", name: "Your module name"}
      });
    }