-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger-adapter.js
101 lines (91 loc) · 2.5 KB
/
logger-adapter.js
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
98
99
100
101
'use strict';
var winston = require('winston');
var Mail = require('winston-mail').Mail;
var Sentry = require('winston-sentry');
var connector;
var config;
var logger;
var throttle = function () {
return Promise.resolve(false);
};
function initThrottle(config) {
var throttleAdapter;
if (!config) {
return;
}
if (!config.adapter) {
return;
}
if (typeof connector.getAdapter === 'function') {
throttleAdapter = connector.getAdapter(config.adapter);
} else {
throttleAdapter = connector[config.adapter];
}
if (!throttleAdapter) {
return;
}
if (typeof throttleAdapter.throttle !== 'function') {
return;
}
throttle = function () {
return Promise.resolve(throttleAdapter.throttle.apply(throttleAdapter, Array.prototype.slice.call(arguments)));
}
}
function convertErrorInsteadOfMsgArgToWinston(args) {
var level = args.shift();
var msg = args.shift();
var meta = args.shift() || {};
var message = msg;
if (msg instanceof Error) {
message = msg.message;
meta = Object.assign(msg, meta);
}
return [level, message, meta];
}
module.exports = {
initAdapter: (_connector, _config) => {
connector = _connector;
config = _config;
logger = new winston.Logger({
transports: [
new winston.transports.Console({level: config.level})
],
levels: {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
silly: 5
},
colors: {
error: 'red',
warn: 'yellow',
info: 'green',
verbose: 'cyan',
debug: 'blue',
silly: 'magenta'
}
});
if (config.enableMails) {
logger.add(Mail, config.mailConfig);
}
if (config.enableSentry) {
logger.add(Sentry, config.sentryConfig);
}
initThrottle(config.throttle);
},
log: function () {
var args = convertErrorInsteadOfMsgArgToWinston([].slice.call(arguments));
throttle.apply(null, args)
.then(isThrottled => {
if (!isThrottled) {
logger.log.apply(logger, args);
}
})
.catch(err => {
logger.log('error', err);
logger.log.apply(logger, args);
});
}
};