Logger.js
2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* 重写日志生成
* @type {exports}
*/
var winston = require('winston');
var _ = require('lodash');
var mkdirp = require('mkdirp');
var _path = require('path');
/**
* 日志配置
* @type {Object}
*/
var logConfig = {};
var log = function (name) {
var flag = false;
if (name == 'error') {
flag = true;
}
logConfig = {
file: name + '.log',
level: name,
trans: {
Console: {
handleExceptions: flag,
colorize: 'all',
prettyPrint: true
},
File: {
filename: "",
maxsize: 50 * 1024 * 1024,
handleExceptions: flag
},
exitOnError: false
}
};
return logConfig;
};
/**
* 配置日志
* @param {String} path 路径
* @param {String} level 日志级别
* @param {Object} transConfig 配置项
* @return {Object} 日志
*/
function configLogger(path, level, transConfig) {
var trans = [], config = {}, consoleOpt, fileOpt;
//配置输出控制台的日志
if (transConfig && transConfig.Console) {
consoleOpt = transConfig.Console;
trans.push(new (winston.transports.Console)(consoleOpt));
}
//配置写文件的日志
if (path) {
transConfig.File.filename = path;
fileOpt = transConfig.File;
trans.push(new (winston.transports.File)(fileOpt));
}
//退出错误配置,进行设置
config.exitOnError = transConfig.exitOnError;
//等级
config.level = level;
config.transports = trans;
//根据配置参数,实例化Winston
var logger = new (winston.Logger)(config);
return logger;
}
/**
* 生成文件路径
* @param {String} logsConfig 文件路径
* @return {Object} 一组日志配置
*/
function init(logsConfig) {
//创建日志目录,路径不存在
var path = logsConfig.src;
if (!path) {
console.error('path can not be null!');
}
//创建目录
try {
mkdirp.sync(path);
} catch (err) {
console.error(err);
path = false;
}
var loggers = {};
var config = {};
_.forEach(logsConfig.consoles, function (v, k) {
config[v] = log(v);
});
_.forEach(config, function (v, k) {
var pathfile = path ? _path.join(path, v.file) : false;
loggers[k] = configLogger(pathfile, v.level, v.trans);
});
return loggers;
}
module.exports = init;