-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
99 lines (81 loc) · 2.37 KB
/
logger.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
'use strict'
const path = require('path')
const util = require('util')
const colors = require('colors')
const gStartTimeMS = Date.now()
colors.setTheme({
debug: 'blue',
info: 'green',
warn: 'yellow',
error: 'red',
fatal: 'red'
})
exports.facility = facility
function facility(filename, overrideLevel) {
const facilityName = filename ? path.basename(filename).split('.')[0] : undefined
function debug(...args) {
emit(Date.now(), facilityName, 'debug', ...args)
}
function info(...args) {
emit(Date.now(), facilityName, 'info', ...args)
}
function warn(...args) {
emit(Date.now(), facilityName, 'warn', ...args)
}
function error(...args) {
emit(Date.now(), facilityName, 'error', ...args)
}
function fatal(...args) {
emit(Date.now(), facilityName, 'fatal', ...args)
}
function dir(obj, options) {
debug(util.inspect(obj, options))
}
function noop() { }
const level = overrideLevel || 'info'
const isDebug = level === 'debug'
const isInfo = isDebug || level === 'info'
const isWarn = isInfo || level === 'warn'
const isError = isWarn || level === 'error'
const isFatal = isError || level === 'fatal'
return {
dir: isDebug ? dir : noop,
log: isDebug ? debug : noop,
debug: isDebug ? debug : noop,
info: isInfo ? info : noop,
warn: isWarn ? warn : noop,
error: isError ? error : noop,
fatal: isFatal ? fatal : noop
}
}
Object.assign(exports, facility())
/**
* Master logging function. All log messages should go through here.
*
* @param {Number} dateMS Timestamp the message was logged
* @param {String} facilityName Facility which logged the messsage
* @param {String} level Level of the log message
* @param {Array} All other arguments are added to the message text
* {Object} Outputs as JSON
* {Error} Outputs the stack field
* {*} Outputs as-is
* @return {undefined}
*/
function emit(dateMS, facilityName, level, ...args) {
let msg = dateMS - gStartTimeMS
msg += ' ' + (level + ':')[level]
if (facilityName)
msg += ' [' + facilityName + ']'
for (let i = 0; i < args.length; ++i) {
const type = typeof args[i]
if (type === 'object') {
if (util.isError(args[i]))
msg += ' ' + args[i].stack
else
msg += ' ' + JSON.stringify(args[i])
} else {
msg += ' ' + args[i]
}
}
console.log(msg) // eslint-disable-line no-console
}