forked from livingdocsIO/loki-log-export
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-logs.js
53 lines (46 loc) · 1.69 KB
/
get-logs.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
const mergeStreams = require('./merge-logs')
const delay = require('util').promisify(setTimeout)
module.exports = function follow (opts) {
const loki = require('axios').create({baseURL: opts.baseURL || 'http://localhost:3100'})
const afterMs = opts.start.getTime ? opts.start.getTime() : Date.parse(opts.start)
const endMs = opts.end.getTime ? opts.end.getTime() : Date.parse(opts.end)
const query = opts.query || '{service="bluewin-test/varnish"}'
return {
[Symbol.asyncIterator]() {
let after = `${afterMs}000000`
const end = `${endMs}000000`
return {
async next() {
let tries = 3
while (tries--) {
try {
opts.log.debug(`Fetch after ${after}, end ${end}`)
const res = await loki({
url: '/loki/api/v1/query_range',
params: {
limit: 1000,
direction: 'forward',
query,
start: after,
end
}
})
if (res.data.status !== 'success') {
throw new Error(`Invalid Loki Result: ${JSON.stringify(res.data)}`)
}
const logs = mergeStreams(res.data.data.result)
if (logs && logs[0] && logs[0].ts === after) logs.shift()
if (!logs.length) return {done: true}
after = logs[logs.length - 1].ts
return {done: false, value: logs}
} catch (err) {
opts.log.error({err}, 'Failed to fetch logs from loki')
}
await delay(1000)
}
throw new Error(`Failed to fetch logs after 3 retries.`)
}
}
}
}
}