Search code examples
javascriptnode.jsloggingwinston

Attaching console transport to Winston logging


So I'm trying to attach console as a transport to winston logger. Below is my code.

winston.add(winston.transports.Console, {
    level: 'info',
    colorize: true,
    timestamp: true,
    json: false,
    stringify: false,
    prettyPrint: true,
    depth: 5,
    humanReadableUnhandledException: true,
    showLevel: true,
    stderrLevels: ['error', 'debug']
});

But when I start the application,I get below error.

C:\Users\xxxxx\yyyyy\javascript\MyApp\node_modules\winston\lib\winston\logger.js:481
    throw new Error('Transport already attached: ' + instance.name + ", assign a different name");
    ^

Error: Transport already attached: console, assign a different name
    at Logger.add (C:\Users\xxxxx\yyyyy\javascript\MyApp\node_modules\winston\lib\winston\logger.js:481:11)
    at Object.winston.(anonymous function) [as add] (C:\Users\xxxxx\yyyyy\javascript\MyApp\node_modules\winston\lib\winston.js:87:34)
    at Object.<anonymous> (C:\Users\xxxxx\yyyyy\javascript\MyApp\app.js:36:9)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\xxxxx\yyyyy\javascript\MyApp\bin\www:7:11)

Now, I understand that my console is already by default attached to the logger. But I am writing this additionally because I want to change the configurations according to my preferences.

Can anyone suggest how do I achieve this? Do I have to put some other syntax in order to change configuration of already attached transport or is there any way around this with the same code I am using?

Please suggest.


Solution

  • If you already have a transport of the same type attached, you need to name the new transport:

    winston.add(winston.transports.Console, {
      name : 'UNIQUE_NAME_HERE',
      level: 'info',
      ...
    });
    

    Documented here.