forked from pinojs/pino-multi-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multistream.js
116 lines (98 loc) · 2.46 KB
/
multistream.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
'use strict'
const metadata = Symbol.for('pino.metadata')
const levels = {
silent: Infinity,
fatal: 60,
error: 50,
warn: 40,
info: 30,
debug: 20,
trace: 10
}
function multistream (streamsArray) {
var counter = 0
streamsArray = streamsArray || []
const res = {
write,
add,
minLevel: 0,
streams: [],
clone,
[metadata]: true
}
if (Array.isArray(streamsArray)) {
streamsArray.forEach(add, res)
} else {
add.call(res, streamsArray)
}
// clean this object up
// or it will stay allocated forever
// as it is closed on the following closures
streamsArray = null
return res
// we can exit early because the streams are ordered by level
function write (data) {
var dest
const level = this.lastLevel
const { streams } = this
var stream
for (var i = 0; i < streams.length; i++) {
dest = streams[i]
stream = dest.stream
if (dest.level <= level) {
if (stream[metadata]) {
const { lastTime, lastMsg, lastObj, lastLogger } = this
stream.lastLevel = level
stream.lastTime = lastTime
stream.lastMsg = lastMsg
stream.lastObj = lastObj
stream.lastLogger = lastLogger
}
stream.write(data)
} else {
break
}
}
}
function add (dest) {
const { streams } = this
if (typeof dest.write === 'function') {
return add.call(this, { stream: dest })
} else if (typeof dest.levelVal === 'number') {
return add.call(this, Object.assign({}, dest, { level: dest.levelVal, levelVal: undefined }))
} else if (typeof dest.level === 'string') {
return add.call(this, Object.assign({}, dest, { level: levels[dest.level] }))
} else if (typeof dest.level !== 'number') {
// we default level to 'info'
dest = Object.assign({}, dest, { level: 30 })
} else {
dest = Object.assign({}, dest)
}
dest.id = counter++
streams.unshift(dest)
streams.sort(compareByLevel)
this.minLevel = streams[0].level
return res
}
function clone (level) {
var streams = new Array(this.streams.length)
for (var i = 0; i < streams.length; i++) {
streams[i] = {
level: level,
stream: this.streams[i].stream
}
}
return {
write,
add,
minLevel: level,
streams,
clone,
[metadata]: true
}
}
}
function compareByLevel (a, b) {
return a.level - b.level
}
module.exports = multistream