UNPKG

1.77 kBJavaScriptView Raw
1const Transport = require('winston-transport')
2const Batcher = require('./src/batcher')
3
4/**
5 * A Winston transport for Grafana Loki.
6 *
7 * @class LokiTransport
8 * @extends {Transport}
9 */
10class LokiTransport extends Transport {
11 /**
12 * Creates an instance of LokiTransport.
13 * @param {*} options
14 * @memberof LokiTransport
15 */
16 constructor (options) {
17 super(options)
18
19 // Pass all the given options to batcher
20 this.batcher = new Batcher({
21 host: options.host,
22 interval: options.interval,
23 json: options.json,
24 batching: options.batching !== undefined ? options.batching : true,
25 clearOnError: options.clearOnError,
26 replaceOnError: options.replaceOnError,
27 replaceTimestamp: options.replaceTimestamp
28 })
29 }
30
31 /**
32 * An overwrite of winston-transport's log(),
33 * which the Winston logging library uses
34 * when pushing logs to a transport.
35 *
36 * @param {*} info
37 * @param {*} callback
38 * @memberof LokiTransport
39 */
40 log (info, callback) {
41 // Immediately tell Winston that this transport has received the log.
42 setImmediate(() => {
43 this.emit('logged', info)
44 })
45
46 // Deconstruct the log
47 const { label, timestamp, level, message, ...rest } = info
48
49 // Construct the log to fit Grafana Loki's accepted format
50 const logEntry = {
51 labels: `{job="${label}", level="${level}"}`,
52 entries: [
53 {
54 ts: timestamp || Date.now(),
55 line: `${message} ${
56 rest && Object.keys(rest).length > 0 ? JSON.stringify(rest) : ''
57 }`
58 }
59 ]
60 }
61
62 // Pushes the log to the batcher
63 this.batcher.pushLogEntry(logEntry)
64
65 // Trigger the optional callback
66 callback()
67 }
68}
69
70module.exports = LokiTransport