-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathindex.ts
74 lines (63 loc) · 1.91 KB
/
index.ts
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
import abstractTransportBuild from 'pino-abstract-transport'
import debug from './debug'
import { LokiLogLevel } from './types'
import { LogPusher } from './log_pusher'
import type { PinoLog, LokiOptions } from './types'
/**
* Resolves the options for the Pino Loki transport
*/
function resolveOptions(options: LokiOptions) {
return {
...options,
timeout: options.timeout ?? 30_000,
silenceErrors: options.silenceErrors ?? false,
batching: options.batching ?? true,
interval: options.interval ?? 5,
replaceTimestamp: options.replaceTimestamp ?? false,
propsToLabels: options.propsToLabels ?? [],
convertArrays: options.convertArrays ?? false,
}
}
function pinoLoki(userOptions: LokiOptions) {
const options = resolveOptions(userOptions)
const logPusher = new LogPusher(options)
debug(`[PinoLoki] initialized with options: ${JSON.stringify(options)}`)
let batchInterval: NodeJS.Timeout | undefined
let pinoLogBuffer: PinoLog[] = []
return abstractTransportBuild(
async (source) => {
if (options.batching) {
batchInterval = setInterval(async () => {
debug(`Batch interval reached, sending ${pinoLogBuffer.length} logs to Loki`)
if (pinoLogBuffer.length === 0) {
return
}
logPusher.push(pinoLogBuffer)
pinoLogBuffer = []
}, options.interval! * 1000)
}
for await (const obj of source) {
if (options.batching) {
pinoLogBuffer.push(obj)
continue
}
logPusher.push(obj)
}
},
{
/**
* When transport is closed, push remaining logs to Loki
* and clear the interval
*/
async close() {
if (options.batching) {
clearInterval(batchInterval!)
await logPusher.push(pinoLogBuffer)
}
},
},
)
}
export default pinoLoki
export type { LokiOptions }
export { LokiLogLevel }