-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
121 lines (101 loc) · 2.38 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
var combiner = require('stream-combiner')
var through2 = require('through2')
var chalk = require('chalk')
var split = require('split')
module.exports = logrus
module.exports.createStream = logrus
var poolCount = 0
var poolIndex = {}
var pool = [
'magenta',
'cyan',
'blue',
'green',
'yellow'
]
var levels = {
error: 'red',
warn: 'yellow',
debug: 'cyan',
info: 'blue'
}
const levelMap = {
error: 'FATA',
warn: 'WARN',
debug: 'DBUG',
info: 'INFO'
}
const epoch = Date.now()
var longest = 0
function logrus (opts) {
opts = opts || {}
return combiner(split(), through2.obj(write))
function safeparse (data) {
try {
data = JSON.parse(data)
} catch(e) { }
return data
}
function write (data, _, next) {
data = safeparse(data)
if (typeof data !== 'object') {
this.push(data)
this.push('\n')
return next()
}
var level = levels[data.level] || 'yellow'
var name = data.name ? data.name.replace(/\:[-:\w]{8,}$/g, '') : ''
var nameColor = poolIndex[name] || (
poolIndex[name] = pool[poolCount++ % pool.length]
)
longest = data.name.length > longest ? data.name.length : longest
const now = new Date(data.time)
delete data.time
const lev = chalk[level](levelMap[data.level])
delete data.level
const time = '[' + numPad((~~((now.getTime() - epoch) / 100)) % 10000) + ']'
const nom = '[' + data.name + ']'
delete data.name
const line = [lev + time, nom]
if (data.message) {
line.push(data.message)
} else if (data.req) {
var req = data.req
line.push(chalk.bold(req.method))
line.push(chalk.green(req.url))
} else if (data.err) {
line.push(data.err.stack)
} else {
line.push(JSON.stringify(data, null, 2))
}
delete data.message
delete data.pid
delete data.hostname
const keys = Object.keys(data).map(prettyKeys(data))
line.push(keys)
this.push(line.join(' '))
this.push('\n')
next()
}
}
function pad (str, n) {
str = String(str)
while (str.length < n) {
str = ' ' + str
}
return str
}
function numPad (num) {
num = String(num)
while (num.length < 4) {
num = '0' + num
}
return num
}
// prettyify keys of an object
function prettyKeys(obj) {
return function map(key) {
const val = obj[key]
return key + '=' + (typeof val == 'string' ? "\"" + val + "\"" : val)
}
}