-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmod.ts
94 lines (89 loc) · 2.29 KB
/
mod.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { RangeOf } from './rangeof.ts';
type Entry = [string, string];
interface Body {
streams: [
{
stream: Record<string, string>;
values: Entry[];
}
];
}
/**
* Loki logger
* @param url path is where LokiLogger will post to
* @param buffer is the amount of entries to cache before sending
* @param labels Labels to use
* @param mode mode to post
*/
export class LokiLogger {
toReport?: Entry[];
constructor(
public url: string = 'http://localhost:3100',
public buffer: RangeOf<50> = 1,
public labels: Record<string, string> = {
host: 'localhost',
job: 'Deno!',
},
public mode: 'JSON' | 'TEXT' = 'TEXT'
) {
if (buffer !== 1) {
this.toReport = [];
}
}
private async pushPayload(entry: Entry) {
if (this.buffer !== 1) this.toReport!.push(entry);
if (this.buffer === this.toReport?.length) {
await this.report(this.createPayload(this.toReport));
//Clear the reports
this.toReport.length = 0;
} else if (this.buffer === 1) {
await this.report(this.createPayload([entry]));
}
}
private createPayload(entries: Entry[]): Body {
return {
streams: [{ stream: this.labels, values: entries }],
};
}
private async report(body: Body) {
//https://github.com/grafana/loki/issues/173
//https://github.com/sleleko/devops-kb/blob/master/python/push-to-loki.py
let r = await fetch(`${this.url}/loki/api/v1/push`, {
headers: { 'Content-type': 'application/json' },
method: 'POST',
body: JSON.stringify(body),
});
if (!r.ok) {
throw new Error(
`FAILED TO POST DATA ${await r.text()} ${JSON.stringify(r)}`
);
}
}
public log(label: string, text: string, meta?: Record<string, string>) {
meta = {
label,
text,
...meta,
};
return this.pushPayload([
`${Date.now()}000000`,
this.mode == 'JSON'
? JSON.stringify(meta)
: Object.entries(meta)
.map(([k, v]) => `${k}="${v}"`)
.join(' '),
]);
}
public info(text: string, meta?: Record<string, string>) {
return this.log('INFO', text, meta);
}
public warm(text: string, meta?: Record<string, string>) {
return this.log('WARN', text, meta);
}
public error(text: string, meta?: Record<string, string>) {
return this.log('ERROR', text, meta);
}
public debug(text: string, meta?: Record<string, string>) {
return this.log('DEBUG', text, meta);
}
}