-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathlog_pusher.ts
79 lines (66 loc) · 1.98 KB
/
log_pusher.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
75
76
77
78
79
import type { Got } from 'got'
import got, { RequestError } from 'got'
import debug from './debug'
import { LogBuilder } from './log_builder'
import type { PinoLog, LokiOptions } from './types'
/**
* Responsible for pushing logs to Loki
*/
export class LogPusher {
#options: LokiOptions
#logBuilder: LogBuilder
#client: Got
constructor(options: LokiOptions) {
this.#options = options
this.#client = got.extend({
...(this.#options.host && { prefixUrl: this.#options.host }),
timeout: { request: this.#options.timeout ?? 30_000 },
headers: options.headers ?? {},
...(this.#options.basicAuth && {
username: this.#options.basicAuth?.username,
password: this.#options.basicAuth?.password,
}),
})
this.#logBuilder = new LogBuilder({
levelMap: options.levelMap,
propsToLabels: options.propsToLabels,
})
}
/**
* Handle push failures
*/
#handleFailure(err: any) {
if (this.#options.silenceErrors === true) {
return
}
if (err instanceof RequestError) {
console.error(
'Got error when trying to send log to Loki:',
err.message + '\n' + err.response?.body,
)
return
}
console.error('Got unknown error when trying to send log to Loki, error output:', err)
}
/**
* Push one or multiples logs entries to Loki
*/
async push(logs: PinoLog[] | PinoLog) {
if (!Array.isArray(logs)) {
logs = [logs]
}
const lokiLogs = logs.map((log) =>
this.#logBuilder.build({
log,
replaceTimestamp: this.#options.replaceTimestamp,
additionalLabels: this.#options.labels,
convertArrays: this.#options.convertArrays,
}),
)
debug(`[LogPusher] pushing ${lokiLogs.length} logs to Loki`)
await this.#client
.post(`loki/api/v1/push`, { json: { streams: lokiLogs } })
.catch(this.#handleFailure.bind(this))
debug(`[LogPusher] pushed ${lokiLogs.length} logs to Loki`, { logs: lokiLogs })
}
}