-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
85 lines (76 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const { Writable } = require("node:stream");
const Tcp = require("./transports/Tcp");
const Udp = require("./transports/Udp");
const LEVELS = {
EMERGENCY: 0,
ALERT: 1,
CRITICAL: 2,
ERROR: 3,
WARNING: 4,
NOTICE: 5,
INFO: 6,
DEBUG: 7,
};
class BunyanToGelfStream extends Writable {
/**
* BunyanToGelfStream
*
* @param options
* @param options.host
* @param options.port
* @param options.protocol Protocol can be 'udp' or 'tcp'
*/
constructor(options = {}) {
super();
this._transport =
options.protocol === "tcp" ? new Tcp(options) : new Udp(options);
}
/**
* Map default bunyan log levels to gelf levels format
*
* @param level
*
* @return {number}
* @private
*/
_mapBunyanLevelToGelf(level) {
switch (level) {
case 10:
return LEVELS.DEBUG;
case 20:
return LEVELS.DEBUG;
case 30:
return LEVELS.INFO;
case 40:
return LEVELS.WARNING;
case 50:
return LEVELS.ERROR;
case 60:
return LEVELS.EMERGENCY;
default:
return LEVELS.WARNING;
}
}
/**
* Write logs to udp socket
*
* @param log
*/
write(log) {
const message = {
host: log.hostname,
timestamp: +new Date(log.time) / 1000,
short_message: log.msg,
facility: log.name,
level: this._mapBunyanLevelToGelf(log.level),
full_message: JSON.stringify(log, null, 2),
};
// Remove gelf ignored fields
const keys = Object.keys(log).filter(key => !['hostname', 'time', 'msg', 'name', 'level', 'v'].includes(key));
keys.forEach(key => {
message[`_${key}`] = log[key];
});
this._transport.send(message);
}
}
module.exports = BunyanToGelfStream;