- Winston是Node.js最流行的日志框架之一,设计为一个简单通用的日志库,支持多传输(在Winston中,一个传输实质上代表储存设备,也就是数据最终保存在哪里),每个Winston实例都可以对不同级别的日志配置不同的传输。
- config.js中的配置
const winston = require('winston');
let initLoggerConfig = function (config) {
/**
* Create logger
*/
let logger = new (winston.Logger)(config.logger),
jobLogger = new(winston.Logger)(config.jobLogger);
config.log = function () {
logger.log(arguments);
};
config.info = function () {
logger.info(arguments);
};
config.error = function () {
logger.error(arguments);
};
config.debug = function () {
logger.debug(arguments);
};
config.jobInfo = function () {
jobLogger.info(arguments);
};
config.jobError = function () {
jobLogger.error(arguments);
};
};
const path = require('path'),
winston = require('winston'),
DailyRotateFile = require('winston-daily-rotate-file');
module.exports = {
env: 'production',
logger: {
transports: [
new winston.transports.Console({
colorize: true
}),
new DailyRotateFile({
level: 'silly',
filename: path.resolve('./logs/access-'),
datePattern: 'yyyy-MM-dd.log',
maxsize: 5242880 /* 5MB */
})
]
},
jobLogger: {
transports: [
new winston.transports.Console({
colorize: true
}),
new DailyRotateFile({
level: 'silly',
filename: path.resolve('./logs/jobs-'),
datePattern: 'yyyy-MM-dd.log',
maxsize: 5242880 /* 5MB */
})
]
},
showErrorStack: process.env.SHOW_ERROR_STACK === 'true',
livereload: false
};
let logger = new (winston.Logger)(config.logger)
为
let logger = new (winston.Logger)(
{
transports: [
new winston.transports.Console({
colorize: true
}),
new DailyRotateFile({
level: 'silly', // 要记录的消息级别。0:error 1:warn 2:info 3:verbose 4:debug 5:silly
filename: path.resolve('./logs/access-'), // 用于将日志数据写入的文件。
datePattern: 'yyyy-MM-dd.log',
maxsize: 5242880 /* 5MB */
})
]
}
)
- 生成日志文件示例
access-2018-11-11.log
jobs-2018-11-11.log
- 使用
config.info('创建审方订单成功2。');
config.error('创建审方订单成功3。');
config.debug('创建审方订单成功4。');
{"level":"info","message":"{ '0': '创建审方订单成功2。' }","timestamp":"2018-11-28T09:57:18.841Z"}
{"level":"error","message":"{ '0': '创建审方订单成功3。' }","timestamp":"2018-11-28T09:57:18.843Z"}
{"level":"debug","message":"{ '0': '创建审方订单成功4。' }","timestamp":"2018-11-28T09:57:18.843Z"}