-
Notifications
You must be signed in to change notification settings - Fork 17
/
tee.js
executable file
·88 lines (72 loc) · 1.88 KB
/
tee.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
#! /usr/bin/env node
'use strict'
const split = require('split2')
const cloneable = require('cloneable-readable')
const pump = require('pump')
const Parse = require('fast-json-parse')
const minimist = require('minimist')
const pino = require('pino')
const transport = require('./transport')
const fs = require('fs')
function tee (origin) {
const clone = cloneable(origin)
clone.tee = function (dest, filter) {
filter = filter || alwaysTrue
pump(this.clone(), buildFilter(filter), dest)
return dest
}
return clone
}
function buildFilter (filter) {
if (typeof filter === 'number') {
const num = filter
filter = function (v) { return v.level >= num }
} else if (typeof filter === 'string') {
const num = pino.levels.values[filter]
if (typeof num === 'number' && isFinite(num)) {
filter = function (v) { return v.level >= num }
} else {
throw new Error('no such level')
}
}
return split(function (line) {
const res = new Parse(line)
if (res.value && filter(res.value)) {
return JSON.stringify(res.value) + '\n'
} else {
return undefined
}
})
}
function alwaysTrue () {
return true
}
module.exports = transport
module.exports.tee = tee
if (require.main === module) {
start()
}
function start () {
const args = minimist(process.argv.slice(2))
const pairs = []
let i
if (args._.length % 2) {
console.error('pino-tee requires an even number of args\nUsage: pino-tee [filter dest].')
process.exit(1)
}
for (i = 0; i < args._.length; i += 2) {
let dest = args._[i + 1]
if (dest === ':2') {
dest = process.stderr
} else {
dest = fs.createWriteStream(dest, { flags: 'a' })
}
pairs.push({
filter: args._[i],
dest
})
}
const instance = tee(process.stdin)
pairs.forEach(pair => instance.tee(pair.dest, pair.filter))
instance.pipe(process.stdout)
}