logger.js - 日志模块 /** * 模块依赖: * winston:日志库 * common:自己的公共库 */let winston = require('winston');let common = require('./common');// 存储路径let path = './storage/logs/';/** * 不暴露方法定义 *
/**
* 模块依赖:
* winston:日志库
* common:自己的公共库
*/
let winston = require('winston');
let common = require('./common');
// 存储路径
let path = './storage/logs/';
/**
* 不暴露方法定义
*/
class Self {
/**
* 获取文件名
*
* @returns {*}
* @private
*/
static _getFile () {
return common.sprintf(path + '%s.log', common.now());
}
/**
* 格式化输出日志
*
* @param options
* @returns {string}
*/
static _logFormatter(options) {
let msg = '';
// 是否有错误码
if (options.meta.code) {
msg = common.sprintf('[时间]: %s; [级别]: %s; [错误码]: %s; [信息]: %s; [文件]: %s; [行数]: %s; [自定义参数]: %s',
common.nowTime(),
options.level,
options.meta.code,
options.message,
__preFile,
__preLine,
JSON.stringify(options.meta.context)
);
} else {
msg = common.sprintf('[时间]: %s; [级别]: %s; [信息]: %s; [文件]: %s; [行数]: %s; [自定义参数]: %s',
common.nowTime(),
options.level,
options.message,
__preFile,
__preLine,
JSON.stringify(options.meta.context)
);
}
return msg;
};
}
/**
* 变量定义
*/
// 获取Logger实例
let logger = new (winston.Logger)({
transports: [
// 输出到Console
new (winston.transports.Console)({
formatter: Self._logFormatter,
json: false
}),
// 输出到File
new (winston.transports.File)({
filename: Self._getFile(),
formatter: Self._logFormatter,
json: false
})
]
});
/**
* 暴露方法
*/
module.exports = {
/**
* 记录Error日志
*/
logError: function (message, code = 500, contextObj = {}) {
logger.error(message, {
code: code,
context: contextObj
});
},
/**
* 记录Warning日志
*/
logWarning: function (message, contextObj = {}) {
logger.warn(message, {
context: contextObj,
});
},
/**
* 记录Info日志
*/
logInfo: function (message, contextObj = {}) {
logger.info(message, {
context: contextObj,
});
},
}
日志使用
var logger = require('./logger');
// 记录日志
logger.logInfo("mig");
logger.logError("aaa", 300, {key: "adfa"});
storage/logs/2017-08-03.log 文件内容示例:
[时间]: 2017-08-03 19:05:27; [级别]: info; [信息]: mig; [文件]: /Users/mingwang/Documents/Project/temp/node/FirstNodeProject/node_modules/winston/lib/winston/common.js; [行数]: 218; [自定义参数]: {}
[时间]: 2017-08-03 19:05:27; [级别]: error; [错误码]: 300; [信息]: aaa; [文件]: /Users/mingwang/Documents/Project/temp/node/FirstNodeProject/node_modules/winston/lib/winston/common.js; [行数]: 218; [自定义参数]: {"key":"adfa"}
common.js - 见公共模块
common.js - 见公共模块
