2016-04-15 36 views
3

我有如下配置:Winston/Node.js如何爲特定環境添加傳輸?

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 
      }) 
] 
}); 

我想補充的郵件傳輸只對生產環境不分期或開發。

我設置了不同的日誌級別如下:

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

有一個辦法做到這一點也與運輸?

回答

5

transports配置只是一個普通的舊Array。所以我們可以使用所有常用的技巧。在這種情況下,你需要一個條件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 
}); 

在填寫郵件配置佔位符後,此代碼在Node.js> = 4上應該可以使用。

相同的原理可應用於exceptionHandlers

相關問題