-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
91 lines (76 loc) · 1.67 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
var combiner = require('stream-combiner')
var through2 = require('through2')
var chalk = require('chalk')
var split = require('split')
module.exports = bistre
module.exports.createStream = bistre
var poolCount = 0
var poolIndex = {}
var pool = [
'magenta'
, 'cyan'
, 'blue'
, 'green'
, 'yellow'
]
var levels = {
error: 'red'
, warn: 'yellow'
, debug: 'cyan'
, info: 'blue'
}
function bistre(opts) {
opts = opts || {}
var showTime = !!opts.time
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 line = []
var name = data.name ? data.name.replace(/\:[-:a-z0-9]{8,}$/g, '') : ''
var nameColor = poolIndex[name] || (
poolIndex[name] = pool[poolCount++ % pool.length]
)
if (showTime) {
line.push(chalk.gray(data.time))
}
line.push(chalk[level](pad(data.level, 5)))
line.push(chalk[nameColor](data.name + ':'))
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))
}
this.push(line.join(' '))
this.push('\n')
next()
}
}
function pad(str, n) {
str = String(str)
while (str.length < 5) {
str = ' ' + str
}
return str
}