-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
525 lines (446 loc) · 17 KB
/
index.ts
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Anyhow: index.ts
/** @hidden */
const _ = require("lodash")
/** @hidden */
let chalk = null
/**
* This is the main (and only) class of the Anyhow library.
* @example const logger = require("anyhow")
*/
class Anyhow {
private static _instance: Anyhow
/** @hidden */
static get Instance() {
return this._instance || (this._instance = new this())
}
// PROPERTIES
// --------------------------------------------------------------------------
/**
* Helper to check if [[setup]] was already called and logger is ready to log.
*/
get isReady() {
if (this._log) {
return true
}
return false
}
/**
* Private logging function. This will be set on [[setup]].
*/
private _log: Function
/**
* Name of the current library being used, populated on setup().
* Possible values are console, winston, bunyan and pino.
*/
private _lib: string = null
/**
* Getter for _lib, to be used by external modules.
*/
get lib() {
return this._lib
}
/**
* Name of the current running app. This will be used when logging
* uncaught exceptions, rejections and in similar cases.
*/
appName: string
/**
* Messages will be compacted (spaces and breaks removed), default is true.
* Set to false to log original values including spaces.
*/
compact: boolean = true
/**
* Prepend logged messages with a timestamp on the format YY-MM-DD hh:mm:ss.
* default is false.
*/
timestamp: boolean = false
/**
* Log error stack traces? Default is false. Use it with care!
* Set to true to add stack traces to the log output.
*/
errorStack: boolean = false
/**
* Include level (INFO, WARN, ERROR etc...) on the output message when
* logging to the console? Default is true.
*/
levelOnConsole: boolean = false
/**
* Array that controls which log calls are enabled. By default
* it's [[info]], [[warn]] and [[error]], so [[debug]] won't log anything.
*/
levels: string[] = ["info", "warn", "error"]
/**
* Set the separator between arguments when generating logging messages.
* Default separator is a pipe symbol " | ".
*/
separator: string = " | "
/**
* Default console logging styles to be used in case the `chalk` module is installed.
* Please check the `chalk` documentation for the available styles.
*/
styles: any = {
/** Display debug logs in gray. */
debug: ["gray"],
/** Display info logs in white. */
info: ["white"],
/** Display warn logs in yellow. */
warn: ["yellow"],
/** Display error messages in bold red. */
error: ["red", "bold"]
}
/**
* A function(arrayOfObjects) that should be called to preprocess the arguments.
* This is useful if you wish to remove or obfuscate data before generating the
* logging message. Can either mutate the passed arguments or return the
* processed array as a result.
*/
preprocessor: Function
/**
* Function to catch and log uncaught exceptions, set by [[uncaughtExceptions]].
*/
private _uncaughtExceptionHandler: Function = null
/**
* Function to catch and log unhandled rejections, set by [[unhandledRejections]].
*/
private _unhandledRejectionHandler: Function = null
/** Returns true if the uncaught exception handler is set, false otherwise. */
get uncaughtExceptions() {
return this._uncaughtExceptionHandler != null
}
/** Enable or disable the uncaught exception handler. */
set uncaughtExceptions(value) {
if (value) {
this._uncaughtExceptionHandler = err => {
this.error(this.appName || "Anyhow", "Uncaught exception", err)
return
}
process.on("uncaughtException" as any, this._uncaughtExceptionHandler as any)
} else {
if (this._uncaughtExceptionHandler) {
process.off("uncaughtException", this._uncaughtExceptionHandler as any)
}
this._uncaughtExceptionHandler = null
}
}
/** Returns true if the unhandled rejection handler is set, false otherwise. */
get unhandledRejections() {
return this._unhandledRejectionHandler != null
}
/** Enable or disable the unhandled rejection handler. */
set unhandledRejections(value) {
if (value) {
this._unhandledRejectionHandler = err => {
this.error(this.appName || "Anyhow", "Unhandled rejection", err)
return
}
process.on("unhandledRejection" as any, this._unhandledRejectionHandler as any)
} else {
if (this._unhandledRejectionHandler) {
process.off("Unhandled rejection", this._unhandledRejectionHandler as any)
}
this._unhandledRejectionHandler = null
}
}
// LOGGING METHODS
// --------------------------------------------------------------------------
/**
* Default logging method.
* @param level String representing the level: error, warn, info, verbose, debug, silly
* @param args Array of arguments to be logged.
* @returns The generated message that was just logged.
*/
log(level: string, args: any | any[]): string {
if (this.levels.indexOf(level.toLowerCase()) < 0) return null
let message = _.isString(args) ? args : this.getMessage(args)
// If setup was not called yet, defaults to console logging and emit warning.
if (!this.isReady) {
console.warn("Anyhow: please call Anyhow's setup() on your application init. Will default to console.log() for now.")
this.console(level, message)
} else {
this._log(level, message)
}
return message
}
/**
* Shortcut to [[log]]("debug", args).
*/
debug(...args: any[]): string {
if (this.levels.indexOf("debug") < 0) return null
if (args.length < 1) return
let params = Array.from(arguments)
let message = this.getMessage(params)
return this.log("debug", message)
}
/**
* Shortcut to [[log]]("info", args).
*/
info(...args: any[]): string {
if (this.levels.indexOf("info") < 0) return null
if (args.length < 1) return
let params = Array.from(arguments)
let message = this.getMessage(params)
return this.log("info", message)
}
/**
* Shortcut to [[log]]("warn", args).
*/
warn(...args: any[]): string {
if (this.levels.indexOf("warn") < 0) return null
if (args.length < 1) return
let params = Array.from(arguments)
let message = this.getMessage(params)
return this.log("warn", message)
}
/**
* Shortcut to [[log]]("error", args).
*/
error(...args: any[]): string {
if (this.levels.indexOf("error") < 0) return null
if (args.length < 1) return
let params = Array.from(arguments)
let message = this.getMessage(params)
return this.log("error", message)
}
/**
* Log directly to the console. This is the default logger handler
* in case no other compatible libraries are found.
* @param level String representing the level: error, warn, info, debug
* @param args Array of arguments to be logged.
* @returns The generated message that was just logged.
*/
console(level: string, args: any): string {
if (this.levels.indexOf(level.toLowerCase()) < 0) return null
let message = _.isString(args) ? args : this.getMessage(args)
// Add level to the output?
if (this.levelOnConsole) {
message = `${level.toUpperCase()}: ${message}`
}
let styledMessage = message
let logMethod = console.log
// Check if console supports the passed level. Defaults to "log".
if (console[level] && level != "debug") {
logMethod = console[level]
}
// Is chalk installed? Use it to colorize the messages.
if (chalk && this.styles) {
let styles = this.styles[level]
let chalkStyle
if (styles) {
chalkStyle = chalk
for (let s of styles) {
chalkStyle = chalkStyle[s]
}
} else {
chalkStyle = chalk.white
}
styledMessage = chalkStyle(message)
}
logMethod(styledMessage)
return message
}
/**
* Setup will try to load compatible loggers, and fall back
* to the console if nothing was found. You can also force
* a specific library to be loaded passing the object directly or
* as string "winston|bunyan|pino|console". Set "none" to disable logging.
* @param lib Optional, force a specific library to be used. If not passed, will try winston then bunyan then console.
* @param options Additional options to be passed to the underlying logging library.
*/
setup(lib?: string | any, options?: any): void {
let found = false
let winston, bunyan, pino
// Set defaults.
lib = lib || "console"
options = options || {}
// Passed "none"? This will effectively disable logging.
if (lib == "none") {
this._lib = null
this._log = function() {
return false
}
return
}
// Passed logger directly? Figure out which one it is based on object info.
if (_.isObject(lib)) {
if (lib.constructor.name == "DerivedLogger" && lib.format && lib.level) {
winston = lib
lib = "winston"
} else if (lib.constructor.name == "Logger" && lib.fields) {
bunyan = lib
lib = "bunyan"
} else if (lib.constructor.name == "Pino" && lib.levels) {
bunyan = lib
lib = "pino"
} else {
console.warn("Anyhow.setup", "Passed object was not recognized as Winston / Bunyan / Pino.")
}
}
// First try Winston. It will check if a Winston logger was passed directly
// as `lib`, or use default logger if passed as string.
if (lib == "winston") {
try {
if (!winston) {
winston = require("winston")
}
this._lib = "winston"
this._log = function(level, message) {
winston.log({level: level, message: message})
}
found = true
} catch (ex) {
/* istanbul ignore next */
console.error("Anyhow.setup", "Could not load winston", ex)
}
}
// Then Bunyan. It will check if a Bunyan logger was passed directly
// as `lib`, or create a default logger if passed as string.
if (lib == "bunyan") {
try {
if (!options.name) {
options.name = "Anyhow"
}
if (!bunyan) {
bunyan = require("bunyan").createLogger(options)
}
this._lib = "bunyan"
this._log = function(level, message) {
bunyan[level](message)
}
found = true
} catch (ex) {
/* istanbul ignore next */
console.error("Anyhow.setup", "Could not load bunyan", ex)
}
}
// Then Pino. It will check if a Pino logger was passed directly
// as `lib`, or create a default logger if passed as string.
if (lib == "pino") {
try {
if (!options.name) {
options.name = "Anyhow"
}
if (!pino) {
pino = require("pino")()
}
this._lib = "pino"
this._log = function(level, message) {
pino[level](message)
}
found = true
} catch (ex) {
/* istanbul ignore next */
console.error("Anyhow.setup", "Could not load pino", ex)
}
}
// No logging libraries found? Fall back to console.
if (!found) {
try {
if (!chalk) {
chalk = require("chalk")
}
} catch (ex) {}
this._lib = "console"
this._log = (level, message) => this.console(level, message)
}
}
/**
* Gets a nice, readable message out of the passed arguments, which can be of any type.
* @param args Any single or collection of objects that will be transformed to a message string.
* @returns Human readable string taken out of the parsed arguments.
*/
getMessage(args: any | any[]): string {
if (arguments.length > 1) {
args = Array.from(arguments)
} else if (!_.isArray(args)) {
args = [args]
}
// Add timestamp to the output?
if (this.timestamp) {
const padLeft = v => {
return v < 10 ? "0" + v.toString() : v.toString()
}
// Get date elements.
const now = new Date()
let year: any = now.getUTCFullYear().toString()
let month: any = now.getUTCMonth() + 1
let day: any = now.getUTCDate()
let hour: any = now.getUTCHours()
let minute: any = now.getUTCMinutes()
let second: any = now.getUTCSeconds()
// Append timestamp to the message.
let timestamp = `${padLeft(year.substring(2))}-${padLeft(month)}-${padLeft(day)} ${padLeft(hour)}:${padLeft(minute)}:${padLeft(second)}`
args.unshift(timestamp)
}
// If the preprocessor returns a value, use it as the new args.
if (this.preprocessor) {
let processedArgs = this.preprocessor(args)
args = processedArgs ? processedArgs : args
}
// Return single string log message.
return this.parseArgsForMessage(args).join(this.separator)
}
/**
* Used by [[getMessage]] to parse and return the individual log strings
* out of the passed arguments. Might run recursively.
* @param args Array of arguments to be parsed.
*/
private parseArgsForMessage(args: any[]): string[] {
let result = []
// Parse all arguments and stringify objects. Please note that fields defined
// on the `removeFields` setting won't be added to the message.
for (let arg of args) {
try {
if (arg != null) {
let stringified = ""
try {
if (_.isArray(arg)) {
result = result.concat(this.parseArgsForMessage(arg))
} else if (_.isError(arg)) {
const arrError = []
// Add error information separately.
if (arg.friendlyMessage) {
arrError.push(arg.friendlyMessage)
}
if (arg.reason) {
arrError.push(arg.reason)
}
if (arg.code) {
arrError.push(arg.code)
}
/* istanbul ignore else */
if (arg.message) {
arrError.push(arg.message)
}
// Only add stack traces if `errorStack` is set.
if (arg.stack && this.errorStack) {
arrError.push(arg.stack)
}
stringified = arrError.join(this.separator)
} else if (_.isObject(arg)) {
stringified = JSON.stringify(arg, null, 2)
} else {
stringified = arg.toString()
}
} catch (ex) {
/* istanbul ignore next */
stringified = arg.toString()
}
// Check if a valid message was taken, and if it needs to be compacted.
/* istanbul ignore else */
if (typeof stringified != "undefined" && stringified !== null) {
if (this.compact) {
stringified = stringified.replace(/(\r\n|\n|\r)/gm, "").replace(/ +/g, " ")
}
result.push(stringified)
}
}
} catch (ex) {
/* istanbul ignore next */
console.error("Anyhow.parseArgsForMessage", ex)
}
}
return result
}
}
// Exports...
export = Anyhow.Instance