forked from chibisafe/chibisafe
-
Notifications
You must be signed in to change notification settings - Fork 56
/
logger.js
69 lines (56 loc) · 1.67 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
const { inspect } = require('util')
const self = {}
// Only show shortened version (time) during development
const short = process.env.NODE_ENV === 'development'
const now = () => {
const time = new Date()
const parsed = {
hours: time.getHours(),
minutes: time.getMinutes(),
seconds: time.getSeconds(),
milliseconds: time.getMilliseconds()
}
if (!short) {
parsed.month = time.getMonth() + 1
parsed.date = time.getDate()
}
// Add leading zeroes and slice
Object.keys(parsed).forEach(key => {
parsed[key] = ('0' + parsed[key]).slice(-2)
})
return (!short ? `${time.getFullYear()}-${parsed.month}-${parsed.date} ` : '') +
`${parsed.hours}:${parsed.minutes}:${parsed.seconds}` +
(short ? `.${String(parsed.milliseconds).padStart(3, '0')}` : '')
}
const clean = item => {
if (typeof item === 'string') return item
const cleaned = inspect(item, { depth: 0 })
return cleaned
}
const write = (content, options = {}) => {
const stream = options.error ? process.stderr : process.stdout
stream.write(`[${now()}] ${options.prefix || ''}${clean(content)}\n`)
}
self.log = write
self.error = (content, options = {}) => {
options.error = true
write(content, options)
}
self.debug = (content, options = {}) => {
if (process.env.NODE_ENV !== 'development') return
write(content, options)
}
self.inspect = (...args) => {
const options = {
colors: true,
depth: Infinity
}
if (args.length > 1 && typeof args[args.length - 1] === 'object') {
Object.assign(options, args[args.length - 1])
args.splice(args.length - 1, 1)
}
for (const arg of args) {
console.log(inspect(arg, options))
}
}
module.exports = self