1 | const Transport = require('winston-transport')
|
2 | const Batcher = require('./src/batcher')
|
3 | const { MESSAGE } = require('triple-beam')
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | class LokiTransport extends Transport {
|
12 | |
13 |
|
14 |
|
15 |
|
16 |
|
17 | constructor (options) {
|
18 | super(options)
|
19 |
|
20 |
|
21 | this.batcher = new Batcher({
|
22 | host: options.host,
|
23 | interval: options.interval,
|
24 | json: options.json,
|
25 | batching: options.batching !== undefined ? options.batching : true,
|
26 | clearOnError: options.clearOnError,
|
27 | replaceOnError: options.replaceOnError,
|
28 | replaceTimestamp: options.replaceTimestamp
|
29 | })
|
30 |
|
31 | this.useCustomFormat = options.format !== undefined
|
32 | this.labels = options.labels
|
33 | }
|
34 |
|
35 | |
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | log (info, callback) {
|
45 |
|
46 | setImmediate(() => {
|
47 | this.emit('logged', info)
|
48 | })
|
49 |
|
50 |
|
51 | const { label, timestamp, level, message, ...rest } = info
|
52 |
|
53 |
|
54 | let labels
|
55 | if (this.labels) {
|
56 | labels = `{level="${level}"`
|
57 | for (let key in this.labels) {
|
58 | labels += `,${key}="${this.labels[key]}"`
|
59 | }
|
60 | labels += '}'
|
61 | } else {
|
62 | labels = `{job="${label}", level="${level}"}`
|
63 | }
|
64 |
|
65 |
|
66 | const line = this.useCustomFormat ? info[MESSAGE] : `${message} ${
|
67 | rest && Object.keys(rest).length > 0 ? JSON.stringify(rest) : ''
|
68 | }`
|
69 |
|
70 |
|
71 | const logEntry = {
|
72 | labels: labels,
|
73 | entries: [
|
74 | {
|
75 | ts: timestamp || Date.now(),
|
76 | line
|
77 | }
|
78 | ]
|
79 | }
|
80 |
|
81 |
|
82 | this.batcher.pushLogEntry(logEntry)
|
83 |
|
84 |
|
85 | callback()
|
86 | }
|
87 | }
|
88 |
|
89 | module.exports = LokiTransport
|