-
Notifications
You must be signed in to change notification settings - Fork 53
/
index.js
95 lines (84 loc) · 2.36 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const Transport = require('winston-transport')
const Batcher = require('./src/batcher')
const { MESSAGE } = require('triple-beam')
/**
* 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,
clearOnError: options.clearOnError,
replaceOnError: options.replaceOnError,
replaceTimestamp: options.replaceTimestamp,
gracefulShutdown: !options.gracefulShutdown
})
this.useCustomFormat = options.format !== undefined
this.labels = options.labels
}
/**
* 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, labels, timestamp, level, message, ...rest } = info
// build custom labels if provided
let lokiLabels
if (this.labels) {
lokiLabels = `{level="${level}"`
for (let key in this.labels) {
lokiLabels += `,${key}="${this.labels[key]}"`
}
if (labels) {
for (let key in labels) {
lokiLabels += `,${key}="${labels[key]}"`
}
}
lokiLabels += '}'
} else {
lokiLabels = `{job="${label}", level="${level}"}`
}
// follow the format provided
const line = this.useCustomFormat ? info[MESSAGE] : `${message} ${
rest && Object.keys(rest).length > 0 ? JSON.stringify(rest) : ''
}`
// Construct the log to fit Grafana Loki's accepted format
const logEntry = {
labels: lokiLabels,
entries: [
{
ts: timestamp || Date.now(),
line
}
]
}
// Pushes the log to the batcher
this.batcher.pushLogEntry(logEntry)
// Trigger the optional callback
callback()
}
}
module.exports = LokiTransport