logger.js
1.84 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
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const {createLogger, format, transports} = require('winston');
const { combine, simple, splat, timestamp } = format;
class Logger {
constructor(loggers) {
this.init(loggers);
}
init(loggers) {
try {
let tps;
let mkdirSync = (dirname) => {
if (fs.existsSync(dirname)) {
return true;
} else {
if (mkdirSync(path.dirname(dirname))) {
fs.mkdirSync(dirname);
return true;
}
}
};
_.each(loggers, logger => {
if (logger.filename) {
mkdirSync(path.dirname(logger.filename));
}
});
tps = [new transports.Console(loggers.console)];
if (!loggers.file.close) {
tps.push(new transports.File(loggers.file));
}
this.defaultLogger = createLogger({
format: combine(
splat(),
simple(),
timestamp()
),
transports: tps,
exitOnError: false
});
} catch (e) {
console.error(e);
}
return this;
}
// 动态改变日志级别
changeLevel(level, name) {
name = name || 'console';
let transport = this.defaultLogger.transports[name];
if (transport) {
transport.level = level;
return true;
} else {
return false;
}
}
get logger() {
return this.defaultLogger;
}
log(...args) {
this.defaultLogger.log.apply(this.defaultLogger, ...args);
}
debug() {
this.defaultLogger.debug.apply(this.defaultLogger, arguments);
}
info(...args) {
this.defaultLogger.info.apply(this.defaultLogger, args);
}
warn() {
this.defaultLogger.warn.apply(this.defaultLogger, arguments);
}
error() {
this.defaultLogger.error.apply(this.defaultLogger, arguments);
}
}
module.exports = Logger;