forked from JaniAnttonen/winston-loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (62 loc) · 1.72 KB
/
index.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
const Transport = require('winston-transport')
const Batcher = require('./src/batcher')
/**
* A Winston transport for Grafana Loki.
*
* @class LokiTransport
* @extends {Transport}
*/
class LokiTransport extends Transport {
/**
* Creates an instance of LokiTransport.
* @param {*} options
* @memberof LokiTransport
*/
constructor (options) {
super(options)
// Pass all the given options to batcher
this.batcher = new Batcher({
host: options.host,
interval: options.interval,
json: options.json,
batching: options.batching !== undefined ? options.batching : true,
clearOnError: options.clearOnError,
replaceOnError: options.replaceOnError,
replaceTimestamp: options.replaceTimestamp
})
}
/**
* An overwrite of winston-transport's log(),
* which the Winston logging library uses
* when pushing logs to a transport.
*
* @param {*} info
* @param {*} callback
* @memberof LokiTransport
*/
log (info, callback) {
// Immediately tell Winston that this transport has received the log.
setImmediate(() => {
this.emit('logged', info)
})
// Deconstruct the log
const { label, timestamp, level, message, ...rest } = info
// Construct the log to fit Grafana Loki's accepted format
const logEntry = {
labels: `{job="${label}", level="${level}"}`,
entries: [
{
ts: timestamp || Date.now(),
line: `${message} ${
rest && Object.keys(rest).length > 0 ? JSON.stringify(rest) : ''
}`
}
]
}
// Pushes the log to the batcher
this.batcher.pushLogEntry(logEntry)
// Trigger the optional callback
callback()
}
}
module.exports = LokiTransport