/
index.js
256 lines (230 loc) · 7.29 KB
/
index.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
'use strict';
const aug = require('aug');
const intersection = require('lodash.intersection');
const serializeObject = require('@firstandthird/serialize-object');
const defaults = {
initLog: false,
filter: [],
unhandledRejection: false,
uncaughtException: false,
blacklist: 'password|token',
exclude: [],
defaultTags: [],
logger: null,
reporters: null,
reporterDefaults: {
filter: [],
throttle: false,
throttleBasedOnTags: false,
exclude: []
}
};
class Logger {
constructor(options) {
this.config = aug(defaults, options);
this.rateLimits = {};
//override filter with env vars
if (process.env.LOGR_FILTER) {
this.config.filter = process.env.LOGR_FILTER.split(',');
}
//override exclude with env vars
if (process.env.LOGR_EXCLUDE) {
this.config.exclude = process.env.LOGR_EXCLUDE.split(',');
}
//be able to override core logger
if (this.config.logger) {
this.logger = this.config.logger;
}
if (this.config.unhandledRejection) {
process.on('unhandledRejection', (reason) => {
this.log(['promise', 'error'], reason);
process.exit(1);
});
}
if (this.config.uncaughtException) {
process.on('uncaughtException', (err) => {
this.log(['exception', 'error'], err);
process.exit(1);
});
}
this.reporters = {};
this.setupReporters();
if (this.config.initLog && this.reporters) {
const enabledReporters = Object.keys(this.reporters).filter(name => this.reporters[name].options.enabled !== false);
const report = {
message: 'Logr initialized',
enabledReporters: enabledReporters.join(',')
};
enabledReporters.forEach(r => {
report[`${r}Filter`] = this.reporters[r].options.filter;
});
this.log(['logr', 'init'], report);
}
}
setupReporters() {
//if no reporters, default to the basic console
if (!this.config.reporters) {
this.config.reporters = {
console: {
reporter: require('./lib/console'),
options: {}
}
};
}
//loop through all reporters and make sure they are valid
Object.keys(this.config.reporters).forEach((reporterName) => this.setupReporter(reporterName));
}
setupReporter(key) {
/*
* Reporter structure
*
* OPTION 1
*
* exports.defaults = {
* }
*
* exports.log = function(options, tags, message) {
* }
*
*
* OPTION 2 - if no options, then can just do
*
* module.exports = function(options, tags, message) {
* }
*/
/*
* Loading Reporters
*
* reporters: {
* name: {
* reporter: require('path/to/reporter'),
* options: {
* project level options
* }
* },
* shorthand(options, tags, message) {
*
* }
*/
let reporterObj = this.config.reporters[key];
//support shorthand of just a simple function
if (typeof reporterObj === 'function') {
reporterObj = {
reporter: reporterObj
};
}
if (!reporterObj.reporter) {
throw new Error('reporters must be registered with { reporter, options }');
}
//pass in a string and then require it
if (typeof reporterObj.reporter === 'string') {
reporterObj.reporter = require(reporterObj.reporter);
}
//support for shorthand version with no defaults
if (typeof reporterObj.reporter === 'function') {
reporterObj.reporter = {
log: reporterObj.reporter,
options: {}
};
}
//make sure reporter log is a function
if (typeof reporterObj.reporter.log !== 'function') {
throw new Error('log must be a function');
}
//merge logr reporter defaults, defaults defined by reporter and options passed in
reporterObj.options = aug(
this.config.reporterDefaults,
reporterObj.reporter.defaults || {},
reporterObj.options || {}
);
//copy global filters into each reporter so only have to check one place
//TODO switch to a lodash merge so dupes don't show up
reporterObj.options.filter = reporterObj.options.filter.concat(this.config.filter);
reporterObj.options.exclude = reporterObj.options.exclude.concat(this.config.exclude);
this.reporters[key] = reporterObj;
// init rate-limiting for this reporter:
this.rateLimits[key] = {};
if (typeof reporterObj.reporter.init === 'function' && reporterObj.options.enabled !== false) {
reporterObj.reporter.init(reporterObj.options);
}
}
serialize(tags, message, options) {
//auto add error tag if its an error
if (options.addErrorTagToErrors === undefined) {
options.addErrorTagToErrors = true;
}
if (message instanceof Error) {
if (tags.indexOf('error') < 0 && options.addErrorTagToErrors) {
tags.push('error');
}
}
return serializeObject(message, options);
}
log(tags, message, options) {
//tags are optional
if (arguments.length === 1) {
message = tags;
tags = [];
}
message = this.serialize(tags, message, this.config);
if (this.config.defaultTags.length !== 0) {
tags = this.config.defaultTags.concat(tags);
}
// message = typeof message === 'object' ? this.serialize(tags, message, this.config) : message;
Object.keys(this.reporters).forEach((name) => {
const messageClone = (typeof message === 'object') ? aug(message) : message;
try {
this.reporterLog(name, tags.slice(0), messageClone, options || {});
} catch (e) {
console.log({ tags, message }); //eslint-disable-line no-console
console.log(e); //eslint-disable-line no-console
}
});
}
reporterLog(reporterName, tags, message, additionalOptions) {
const reporterObj = this.reporters[reporterName];
if (additionalOptions && additionalOptions[reporterName]) {
reporterObj.options = aug(reporterObj.options, additionalOptions[reporterName]);
}
const options = reporterObj.options;
//reporters can be disabled on the option level
if (options.enabled === false) {
return;
}
//if there are filters and it doesn't match, stop here
if (options.filter.length !== 0 && intersection(options.filter, tags).length === 0) {
return;
}
//if there are excludes and they match, stop here
if (options.exclude.length !== 0 && intersection(options.exclude, tags).length > 0) {
return;
}
// if throttling was specified then throttle log rate:
if (options.throttle) {
const tagKey = options.throttleBasedOnTags ? tags.join('') : 'all';
const curTime = new Date().getTime();
if (this.rateLimits[reporterName][tagKey]) {
if (curTime - this.rateLimits[reporterName][tagKey] < options.throttle) {
return;
}
}
this.rateLimits[reporterName][tagKey] = curTime;
}
//pass in the options, tag and message to reporter
const out = reporterObj.reporter.log(reporterObj.options, tags, message);
//check if anything meaningful was returned
if (!out) {
return;
}
//pass ouput string to logger
this.logger(out);
}
logger(msg) {
console.log(msg); //eslint-disable-line no-console
}
}
Logger.createLogger = function(options) {
const logr = new Logger(options);
return logr.log.bind(logr);
};
module.exports = Logger;