This repository has been archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
461 lines (392 loc) · 13.3 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var winston = require('winston');
var fluentd = require('fluent-logger');
var DailyRotateFile = require('winston-daily-rotate-file');
var FluentTransport = fluentd.support.winstonTransport();
var logger = Object.create(winston);
logger._defaultLevels = {
uncaughtException: 0,
error : 1,
warn : 2,
info : 3,
verbose : 4
};
module.exports = logger;
/**
* overwrites default settings of the logger module, setups logging transports
* according to provided options object
*
* @public
* @param {Object} options
* @param {Boolean} [options.exitOnError=true]
* @param {Array<Object>} options.transports
* @param {String} options.transports[].type - console|file|fluentd
* @param {String} [options.transports[].level] - maximum allowed level logging restriction
* @param {String} [options.transports[].priority] - 1 = highest priority, determines whether this transport will be selected as default logging solution for 'fault' reports
*/
logger.reinitialize = function reinitialize(options) {
options = logger._sanitizeOptions(options);
logger._options = options;
Object.keys(logger.loggers.loggers).forEach(function(name) {
if (name.match(/^fallback-logger-\d+$/)) {
logger.loggers.close(name);
}
});
if (Array.isArray(options.transports)) {
var defaultTransports = logger._buildPrimaryTransports('fault');
logger.configure({
transports: defaultTransports,
rewriters: [errorTraceFormater],
filters: [errorMessageSanitizer]
});
logger.setLevels(logger._defaultLevels);
}
if (typeof options.exitOnError === 'boolean') {
logger.exitOnError = options.exitOnError;
}
};
/**
* @private
* @param {String} tag
* @param {Object} [transportOptions] - ovewrites defaults
* @return {Array<Transport>}
*/
logger._buildPrimaryTransports = function _buildPrimaryTransports(tag, transportOptions) {
if (typeof tag !== 'string' || !tag) {
throw new Error('`tag` argument must be valid string value');
}
var out = [];
var transports = (logger._options && logger._options.transports) || [];
var index = 0;
var transport;
//trasnports are expected to be sorted by now (higher priority comes first)
while( _.isPlainObject(transports[index])
&& transports[index].priority == transports[0].priority
) {
var opt = _.assign({}, transports[index], transportOptions || {});
transport = logger._buildTransport(tag, opt, index);
out.push(transport);
index++;
}
return out;
};
/**
* @private
* @param {Object} [options]
* return {Object}
*/
logger._sanitizeOptions = function(options) {
options = _.cloneDeep(options || {});
var defaults = {
exitOnError: true,
transports: []
};
options = _.assign(defaults, options);
for (var i = 0, transport = null; i < options.transports.length; i++) {
transport = options.transports[i];
if (typeof transport !== 'object' || transport === null) {
source.splice(index, 1);
continue;
}
if ( typeof transport.priority !== 'number'
|| parseInt(transport.priority) === NaN
) {
transport.priority = Infinity;
}
}
options.transports.sort(function(a, b) {
if (a.priority < b.priority) {
return -1;
} else if (a.priority > b.priority) {
return 1;
} else {
if (a.type == 'file' && b.type == 'fluentd') {
return 1;
} else if (a.type == 'fluentd' && b.type == 'file') {
return -1;
} else {
return 0;
}
}
});
return options;
};
/**
* The returned fallback logger implemets 'error' & `info` method
*
* @private
* @param {String} tag - the tag of a transport the fallback logger should be builded for
* @param {Integer} index - _options.transports index of the transport a fallback logger should be generated for
* @return {Logger|console}
*/
logger._getOrBuildFallbackLogger = function getOrBuildFallbackLogger(tag, index) {
if (index == -1 || logger._options.transports.length-1 <= index) {
return console;
} else {
var newLogger = logger.loggers.add('fallback-logger-'+index, {
transports: [
logger._buildTransport(tag, logger._options.transports[index+1], index+1)
]
});
newLogger.emitErrs = false;
return newLogger;
}
};
/**
* @public
* @param {String} name - user defined logger name (key)
* @param {Object} [createOptions] - used when a logger with the name does not exist yet and is to be created
* @param {String} [createOptions.type] - file|fluentd|console
* @return {Logger}
*/
logger.getOrBuildLogger = function getOrBuildLogger(name, createOptions) {
//logger.get | logger.add is the same function so it must be handled this way
if (logger.loggers.has(name)) {
return logger.loggers.get(name);
}
var options = {transports: []};
var index, transportOptions;
createOptions = createOptions || {};
if (typeof createOptions.type === 'string' && createOptions.type) {
index = _.findIndex(logger._options.transports, function(val) {
return val.type === createOptions.type;
});
if (index === -1) {
throw new Error(`Transport: ${createOptions.type} not found`);
}
transportOptions = _.cloneDeep(logger._options.transports[index]);
if (createOptions) {
_.assign(transportOptions, createOptions);
}
options.transports.push(logger._buildTransport(name, transportOptions, index));
} else {
options.transports = logger._buildPrimaryTransports(name, createOptions);
}
var newLogger = logger.loggers.add(name, options);
if (createOptions && createOptions.levels) {
newLogger.setLevels(_.assign({}, createOptions.levels));
}
return newLogger;
};
/**
* @private
* @param {String} tag
* @param {Object} options - transport options
* @param {String} options.type - currently supported: file|fluentd
* @param {Integer} [transportIndex]
* @return {Transport}
*/
logger._buildTransport = function buildTransport(tag, options, transportIndex) {
options = options || {};
var transport;
if (transportIndex === undefined || transportIndex === null) {
transportIndex = -1;
}
var fallbackLogger = logger._getOrBuildFallbackLogger(tag, transportIndex);
switch (options.type) {
case 'fluentd':
transport = logger.buildFluentTransport(tag, _.assign({
internalLogger: fallbackLogger
}, options));
break;
case 'file':
transport = logger.buildDailyFileTransport(tag, _.assign({
internalLogger: fallbackLogger
}, options));
break;
case 'console':
transport = new winston.transports.Console(options);
break;
default:
throw new Error('Unsupported Transport type: ' + options.type);
}
return transport;
};
/**
* @public
* @param {String} filename
* @param {Object} options
* @param {String} options.dir - logs dirrectory
* @param {String} [options.level] - maximum allowed level logging restriction
* @param {Integer} [option.priority=Infinity] - 1 = highest priority
* @param {Boolean} [options.json=false] - if false, data will be written in pretty printed format
* @param {Boolean} [options.autocreate=true] - whether to automatically create destination dirrectory if it does not exist
* @param {Logger|console} [options.internalLogger]
*
* @return {Transport}
*/
logger.buildDailyFileTransport = function(filename, options) {
options = options || {};
var destination;
if (!options.dir) {
throw new Error('`dir` option is required. (Logs file system location)')
} else if (path.isAbsolute(options.dir)) {
destination = path.resolve(options.dir + path.sep);
} else {
destination = path.resolve(process.cwd() + path.sep + options.dir + path.sep);
}
if (!filename || typeof filename !== 'string') {
throw new Error('`filename` argument must be valid string');
}
var transport = new DailyRotateFile({
level : options.level,
filename : destination + path.sep + filename,
datePattern : '.yy-MM-dd.json',
message : '%l $e $m',
subject : '%l $e $m',
region : 'eu-west-1',
tailable : true,
prettyPrint : true,
json : options.json,
maxSize : 5242880, //5mb
maxFiles : 2,
colorize : false,
handleException : false
});
transport.fallbackLogger = options.internalLogger;
transport.on('error', function(err) {
if (err) {
this.fallbackLogger.error(err);
}
});
if (options.autocreate === undefined || options.autocreate === true) {
logger._ensureFSPathExists(destination, transport);
}
return transport;
};
/**
* @public
* @param {String} tagPostfix
* @param {Object} options
* @param {String} options.host
* @param {Integer} options.port
* @param {String} [options.origin] - logs source identifier (tag)
* @param {String} [options.level] - maximum allowed level logging restriction
* @param {Integer} [options.reconnectInterval]
* @param {Integer} [options.timeout]
* @param {Integer} [options.priority] - determines whether this transport will be selected as default logging solution for 'fault' reports
* @param {String} [options.internalLogger=console]
*
* @return {Transport}
*/
logger.buildFluentTransport = function buildFluentTransport(tagPostfix, options) {
options = options || {};
var tag = '';
if (!tagPostfix || typeof tagPostfix !== 'string') {
throw new Error('`tag` - the first argument must be valid string');
}
switch (process.env.NODE_ENV) {
case 'development':
tag += 'webdev-local';
break;
case 'develop':
tag += 'webdev-dev';
break;
case 'preprod':
tag += 'webdev-preprod';
break;
case 'production':
tag += 'webdev-prod';
break;
default:
tag += 'webdev-local';
}
tag += '.' + (options.origin || ''); // eg. 'webdev-local.bi-depot
tag += '.' + tagPostfix; // eg. 'webdev-local.bi-depot.fault
var transport = new FluentTransport(tag, {
internalLogger : options.internalLogger || console,
host : options.host,
port : options.port,
timeout : options.timeout,
reconnectInterval : options.reconnectInterval
});
transport.level = options.level;
transport.sender._setupErrorHandler();
transport.sender.on('connect', function() {
transport.sender._flushSendQueue();
});
transport.fallbackLogger = transport.sender.internalLogger;
transport.on('error', function(err) {
this.sender.internalLogger.error(err);
});
return transport;
};
/**
* @private
* @param {String} path
* @param {Transport} transport - file transport
*/
logger._ensureFSPathExists = function(path, transport) {
var stat;
try {
stat = fs.statSync(path);
if (stat && !stat.isDirectory()) {
throw new Error(`${path} already exists and is NOT a dirrectory. Can not create log destination`);
}
} catch(e) {
if (e.code == 'ENOENT') {
return fs.mkdirSync(path);
}
throw e;
}
};
//set default logger
logger.reinitialize({
transports: [
{
type: 'file',
priority: 1,
dir: path.resolve(process.cwd() + '/logs/'),
level: 'error',
autocreate: true
}
]
});
//handle uncaughtExceptions
process.on('uncaughtException', function(e) {
logger.uncaughtException(e, function(err) {
if (err) {
console.error(err);
}
if (logger.exitOnError) {
process.exit(1);
}
});
});
/**
* @param {String} level
* @param {String} msg
* @param {Object} meta
*
* @return {undefined}
*/
function errorMessageSanitizer(level, msg, meta) {
if (!msg && meta.message && meta.trace) { //we are dealing with an Error log
msg = meta.message;
delete meta.message;
}
return msg;
}
/**
* @param {String} level
* @param {String} msg
* @param {Object} meta
*/
function errorTraceFormater(level, msg, meta) {
var out, errorConstructor;
if (meta instanceof Error) {
if (typeof meta.toLogger === 'function') {
out = meta.toLogger();
} else if (typeof meta.toJSON === 'function') {
out = meta.toJSON();
}
errorConstructor = Object.getPrototypeOf(meta).constructor;
out = out || {};
out.trace = winston.exception.getTrace(meta);
out.name = errorConstructor && errorConstructor.name;
out.message = meta.message;
}
return out || meta;
}