A better solution is to use a single logger with a format function as a "level filter" to specify which transport logs which specific level. Here is the solution (note, levelFilter
could easily be extended to take an array of acceptable levels).
The key insight is that if no info
object is returned from the formatter chain, nothing gets logged.
const { createLogger, format, transports } = require('winston');
const levelFilter = (level) =>
format((info, opts) => {
if (info.level != level) { return false; }
return info;
})();
const logger = createLogger({
transports: [
new transports.Console({
format: format.combine(
levelFilter("info"),
format.json()
)
}),
new transports.File({
filename: "test.log",
format: format.combine(
levelFilter("error"),
format.json()
)
}),
]
});
// ONLY is logged to test.log
logger.log({
level: 'error',
message: 'abcd'
});
// ONLY is logged to console
logger.log({
level: 'info',
message: '1234'
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…