我有以下配置:
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: 'xxxxxx@xxxxxx.xx',
from: 'winston@xxxxx.xx',
subject: 'Errors occurred',
level: 'error',
host: 'smtp.xxxxx.xx',
username: 'xxxx@xxxx.xx',
password: 'xxxxx',
port: xxx
})
],
exceptionHandlers: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: './logs/exceptions.log' }),
new (Mail)({
to: 'xxxxxx@xxxxxx.xx',
from: 'winston@xxxxx.xx',
subject: 'Errors occurred',
level: 'error',
host: 'smtp.xxxxx.xx',
username: 'xxxx@xxxx.xx',
password: 'xxxxx',
port: xxx
})
]
});
我想仅为生产环境添加邮件传输,而不是在暂存或开发中添加。
我设置了不同的日志级别,如下所示:
if (process.env.NODE_ENV === 'development') {
logger.transports.console.level = 'debug';
logger.transports.file.level = 'debug';
}
有一种方法可以通过运输来做到这一点吗?
答案 0 :(得分:10)
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 : 'xxxxxx@xxxxxx.xx',
from : 'winston@xxxxx.xx',
subject : 'Errors occurred',
level : 'error',
host : 'smtp.xxxxx.xx',
username : 'xxxx@xxxx.xx',
password : 'xxxxx',
port : 1234
}));
}
const logger = new winston.Logger({
transports
});
在填写邮件配置占位符后,此代码应该可以在Node.js> = 4上使用。
同样的原则可以适用于exceptionHandlers
。