2016-04-15 14 views
3

Ich habe die Folge Konfiguration: nur für Produktionsumgebung nicht in der Inszenierung oder EntwicklungWinston/Node.js wie fügen Sie einen Transport nur für bestimmte Umgebungen hinzu?

var winston = require('winston'); 
var Mail = require('winston-mail').Mail; 

var logger = new (winston.Logger)({ 
    transports: [ 
    new (winston.transports.Console)({ level: 'info', colorize: true }), 
    new (winston.transports.File)({ level: 'info', filename: './logs/logs.log', 
    new (Mail)({ 
       to: '[email protected]', 
       from: '[email protected]', 
       subject: 'Errors occurred', 
       level: 'error', 
       host: 'smtp.xxxxx.xx', 
       username: '[email protected]', 
       password: 'xxxxx', 
       port: xxx 
      }) 
    ], 
    exceptionHandlers: [ 
    new (winston.transports.Console)(), 
    new (winston.transports.File)({ filename: './logs/exceptions.log' }), 
    new (Mail)({ 
       to: '[email protected]', 
       from: '[email protected]', 
       subject: 'Errors occurred', 
       level: 'error', 
       host: 'smtp.xxxxx.xx', 
       username: '[email protected]', 
       password: 'xxxxx', 
       port: xxx 
      }) 
] 
}); 

Ich mag würde den Mail-Transport hinzufügen.

stelle ich eine andere Protokollebene wie folgt:

if (process.env.NODE_ENV === 'development') { 
    logger.transports.console.level = 'debug'; 
    logger.transports.file.level = 'debug'; 
} 

es eine Möglichkeit, dass mit dem Transport auch zu tun ist?

Antwort

5

Die transports Konfiguration ist nur eine einfache alte Array. Wir können also alle üblichen Tricks anwenden. In diesem Fall möchten Sie eine bedingte push().

const winston = require('winston'); 
const transports = [ 
    new winston.transports.Console({ 
     level : 'info', 
     colorize : true 
    }), 
    new winston.transports.File({ 
     level : 'info', 
     filename : './logs/logs.log' 
    }) 
]; 

if (process.env.NODE_ENV === 'production') { 
    const Mail = require('winston-mail').Mail; 

    transports.push(new Mail({ 
     to  : '[email protected]', 
     from  : '[email protected]', 
     subject : 'Errors occurred', 
     level : 'error', 
     host  : 'smtp.xxxxx.xx', 
     username : '[email protected]', 
     password : 'xxxxx', 
     port  : 1234 
    })); 
} 

const logger = new winston.Logger({ 
    transports 
}); 

soll Dieser Code verwendbar sein als auf Node.js ist> = 4, nachdem sie in dem Mail-Konfiguration Platzhalter füllen.

Das gleiche Prinzip kann auf die exceptionHandlers angewendet werden.