-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
239 lines (205 loc) · 7.26 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
const os = require('os');
const net = require('net');
const secNet = require('tls');
const http = require('http');
const https = require('https');
const Transport = require('winston-transport');
const debug = require('debug')('winston-log2gelf');
const WINSTON_LEVELS = {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
silly: 5
};
class Log2gelf extends Transport {
constructor(options) {
super(options);
this.name = options.name || 'log2gelf';
this.hostname = options.hostname || os.hostname();
this.host = options.host || '127.0.0.1';
this.port = options.port || 12201;
this.protocol = options.protocol || 'tcp';
this.reconnect = options.reconnect || 0;
this.wait = options.wait || 1000;
this.keepAlive = options.keepAlive || 5000;
this.timeout = options.timeout;
this.exitOnError = options.exitOnError || false;
this.exitDelay = options.exitDelay || 2000;
this.service = options.service || 'nodejs';
this.level = options.level || 'info';
this.silent = options.silent || false;
this.environment = options.environment || 'development';
this.release = options.release;
this.protocolOptions = options.protocolOptions || {};
this.disableMessageSanification = options.disableMessageSanification || false;
this.legacyFormat = options.legacyFormat || false;
this.customPayload = {};
Object.keys(options).forEach((key) => {
if (key[0] === '_') this.customPayload[key] = options[key];
});
// set protocol to use
if (this.protocol === 'tcp' || this.protocol === 'tls') this.setupTCP();
else if (this.protocol === 'http' || this.protocol === 'https') this.setupHTTP();
else throw new TypeError('protocol shoud be one of the following: tcp, tls, http or https');
}
/**
* Parse winston level as a string and return its equivalent numeric value
* @param { String }
* @return {int} level
*/
// eslint-disable-next-line
levelToInt(level) {
return WINSTON_LEVELS[level] || 0;
}
/**
* Open a TCP socket and setups logger funtions
*/
setupTCP() {
const options = Object.assign({
host: this.host,
port: this.port,
rejectUnauthorized: false
}, this.protocolOptions);
// whether or not tls is required
let clientType;
if (this.protocol === 'tls') clientType = secNet;
else clientType = net;
const client = clientType.connect(options);
if (this.keepAlive >= 0) {
client.setKeepAlive(true, this.keepAlive);
}
client.on('connect', () => {
debug('Connected to Graylog server');
client.reconnect = 0;
});
if (this.timeout >= 0) {
client.setTimeout(this.timeout);
client.on('timeout', () => {
debug('Timeout to Graylog server');
client.end();
});
}
client.on('end', () => {
debug('Disconnected from Graylog server');
});
client.on('error', (err) => {
debug('Error connecting to Graylog:', err.message);
client.reconnect = client.reconnect + 1 || 0;
});
client.on('close', () => {
if (!client.ended && (this.reconnect < 0 || client.reconnect < this.reconnect)) {
client.timeout_id = setTimeout(() => {
client.timeout_id = null;
client.connect(options);
}, this.wait);
}
});
this.send = (msg) => {
client.write(`${msg}\0`);
};
this.end = () => {
if (client.timeout_id) {
clearTimeout(client.timeout_id);
}
client.ended = true;
client.end();
};
}
/**
* Set HTTP(S) connection and setup logger function
*/
setupHTTP() {
const headers = Object.assign({
'Content-Type': 'application/json'
}, this.protocolOptions && this.protocolOptions.headers);
const clientType = this.protocol === 'https' ? https : http;
const options = Object.assign(
{
port: this.port,
hostname: this.host,
path: '/gelf',
method: 'POST',
rejectUnauthorized: false,
agent: new clientType.Agent({
keepAlive: this.keepAlive >= 0,
keepAliveMsecs: this.keepAlive
})
},
this.protocolOptions,
{
headers
}
);
this.send = (msg) => {
options.headers['Content-Length'] = Buffer.byteLength(msg);
const req = clientType.request(options/* , (res) => {
// usefull for debug
// console.log('statusCode: ', res.statusCode);
} */ /* eslint-disable-line */);
req.on('error', (e) => {
debug('Error connecting to Graylog:', e.message);
});
req.write(msg);
req.end();
};
}
/**
* Handle log message
* @param { Object } info – log object
* @param { Function } callback
*/
log(info, callback) {
if (this.silent) {
callback();
return;
}
const shortMessage = (typeof info.message === 'string' || info.message instanceof String) ? info.message.split('\n')[0] : info.message;
let fullMessage;
if (this.legacyFormat) {
const meta = {};
Object.keys(info).forEach((key) => {
if (key !== 'error' && key !== 'level') meta[key] = info[key];
});
fullMessage = JSON.stringify(meta, null, 2);
}
else {
fullMessage = info.message;
}
const payload = {
version: '1.1',
timestamp: Date.now() / 1000,
level: this.levelToInt(info.level),
host: this.hostname,
short_message: shortMessage,
full_message: fullMessage,
_service: this.service,
_environment: this.environment,
_release: this.release
};
if (!this.legacyFormat) {
Object.keys(info).forEach((key) => {
if (key !== 'error' && key !== 'level' && key !== 'message' && key !== 'id') {
let value = info[key];
if (!this.disableMessageSanification) {
const valueType = typeof value;
if (valueType !== 'string' && valueType !== 'number') value = JSON.stringify(value);
}
payload[`_${key}`] = value;
}
});
}
const gelfMsg = Object.assign({}, payload, this.customPayload);
this.send(JSON.stringify(gelfMsg));
// as we can't know when tcp is sent, delay cb for 2secs
if (info.exception && this.exitOnError) {
setTimeout(() => {
this.end();
process.exit(1);
}, this.exitDelay);
}
callback();
}
}
module.exports = Log2gelf;