-
Notifications
You must be signed in to change notification settings - Fork 95
/
winston-papertrail.js
484 lines (404 loc) · 14.3 KB
/
winston-papertrail.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*
* winston-papertrail.js:
*
* Transport for logging to Papertrail Service
* www.papertrailapp.com
*
* (C) 2013 Ken Perkins
* MIT LICENCE
*
*/
var os = require('os'),
net = require('net'),
tls = require('tls'),
syslogProducer = require('glossy').Produce,
util = require('util'),
winston = require('winston');
/**
* Papertrail class
*
* @description constructor for the Papertrail transport
*
* @param {object} options options for your papertrail transport
*
* @param {string} options.host host for papertrail endpoint
*
* @param {Number} options.port port for papertrail endpoint
*
* @param {Boolean} [options.disableTls] disable TLS connections, enabled by default
*
* @param {string} [options.hostname] name for the logging hostname in Papertrail
*
* @param {string} [options.program] name for the logging program
*
* @param {string} [options.facility] syslog facility for log messages
*
* @param {string} [options.level] log level for your transport (info)
*
* @param {string} [options.levels] custom mapping of log levels (npm levels to RFC5424 severities)
*
* @param {Function} [options.logFormat] function to format your log message before sending
*
* @param {Number} [options.attemptsBeforeDecay] how many reconnections should
* be attempted before backing of (5)
*
* @param {Number} [options.maximumAttempts] maximum attempts before
* disabling buffering (25)
*
* @param {Number} [options.connectionDelay] delay between
* reconnection attempts in ms (1000)
*
* @param {Boolean} [options.handleExceptions] passed to base Transport (false)
*
* @param {Boolean} [options.colorize] enable colors in Papertrail (false)
*
* @param {Number} [options.depth] max depth for objects dumped by NodeJS util.inspect
*
* @param {Number} [options.maxDelayBetweenReconnection] when backing off,
* what's the max time between
* reconnections (ms)
*
* @param {Boolean} [options.inlineMeta] inline multi-line messages (false)
*
* @param {Boolean} [options.flushOnClose] send remaining messages before closing (false)
*
* @type {Function}
*/
var Papertrail = exports.Papertrail = function (options) {
var self = this;
winston.Transport.call(self, options);
self._KEEPALIVE_INTERVAL = 15 * 1000;
options = options || {};
self.name = 'Papertrail';
self.level = options.level || 'info';
self.depth = options.depth || null;
// Default npm log levels
self.levels = options.levels || {
silly: 7,
debug: 7,
verbose: 7,
info: 6,
warn: 4,
error: 3
};
// Papertrail Service Host
self.host = options.host;
// Papertrail Service Port
self.port = options.port;
// Disable TLS connections (enabled by default)
self.disableTls = typeof options.disableTls === 'boolean' ? options.disableTls : false;
// Hostname of the current app
self.hostname = options.hostname || os.hostname();
// Program is an affordance for Papertrail to name the source of log entries
self.program = options.program || 'default';
// Syslog facility to log messages as to Papertrail
self.facility = options.facility || 'daemon';
// Send ANSI color codes through to Papertrail
self.colorize = options.colorize || false;
// Format your log messages prior to delivery
self.logFormat = options.logFormat || function (level, message) {
return level + ' ' + message;
};
// Number of attempts before decaying reconnection
self.attemptsBeforeDecay = options.attemptsBeforeDecay || 5;
// Maximum number of reconnection attempts before disabling buffer
self.maximumAttempts = options.maximumAttempts || 25;
// Delay between normal attempts
self.connectionDelay = options.connectionDelay || 1000;
// Handle Exceptions
self.handleExceptions = options.handleExceptions || false;
// Maximum delay between attempts
self.maxDelayBetweenReconnection =
options.maxDelayBetweenReconnection || 60000;
// Maximum buffer size (default: 1MB)
self.maxBufferSize =
options.maxBufferSize || 1 * 1024 * 1024;
// Inline meta flag
self.inlineMeta = options.inlineMeta || false;
self.flushOnClose = options.flushOnClose || false;
self.producer = new syslogProducer({ facility: self.facility });
self.currentRetries = 0;
self.totalRetries = 0;
self.buffer = '';
self.loggingEnabled = true;
self._shutdown = false;
// Error out if we don't have a host or port
if (!self.host || !self.port) {
throw new Error('Missing required parameters: host and port');
}
// Open the connection
connectStream();
function cleanup() {
self._erroring = true;
try {
if (self.socket) {
self.socket.destroy();
//this throws some uncatchable thing, eww.
//self.socket.end();
self.socket = null;
}
}
catch (e) { }
try {
if (self.stream) {
//we're cleaning up, don't loop.
self.stream.removeListener('end', connectStream);
self.stream.removeListener('error', onErrored);
self.stream.destroy();
self.stream = null;
}
}
catch (e) { }
self._erroring = false;
}
function wireStreams() {
self.stream.once('error', onErrored);
// If we have the stream end, simply reconnect
self.stream.once('end', connectStream);
}
// Opens a connection to Papertrail
function connectStream() {
// don't connect on either error or shutdown
if (self._shutdown || self._erroring) {
return;
}
cleanup();
try {
if (self.disableTls) {
self.stream = net.createConnection(self.port, self.host, onConnected);
self.stream.setKeepAlive(true, self._KEEPALIVE_INTERVAL);
wireStreams();
}
else {
var socket = net.createConnection(self.port, self.host, function () {
socket.setKeepAlive(true, self._KEEPALIVE_INTERVAL);
self.stream = tls.connect({
socket: socket,
rejectUnauthorized: false
}, onConnected);
wireStreams();
});
socket.on('error', onErrored);
self.socket = socket;
}
}
catch (e) {
onErrored(e);
}
}
self._reconnectStream = connectStream;
function onErrored(err) {
// make sure we prevent simultaneous attempts to connect and handle errors
self._erroring = true;
self._silentErrorEmitter(err);
// We may be disconnected from the papertrail endpoint for any number of reasons;
// i.e. inactivity, network problems, etc, and we need to be resilient against this
// that said, we back off reconnection attempts in case Papertrail is truly down
setTimeout(function () {
// Increment our retry counts
self.currentRetries++;
self.totalRetries++;
// Decay the retry rate exponentially up to max between attempts
if ((self.connectionDelay < self.maxDelayBetweenReconnection) &&
(self.currentRetries >= self.attemptsBeforeDecay)) {
self.connectionDelay = self.connectionDelay * 2;
self.currentRetries = 0;
}
// Stop buffering messages after a fixed number of retries.
// This is to keep the buffer from growing unbounded
if (self.loggingEnabled && (self.totalRetries >= (self.maximumAttempts)))
{
self.loggingEnabled = false;
self._silentErrorEmitter(new Error('Max entries eclipsed, disabling buffering'));
}
// continue
self._erroring = false;
connectStream();
}, self.connectionDelay);
}
function onConnected() {
// Reset our variables
self.loggingEnabled = true;
self.currentRetries = 0;
self.totalRetries = 0;
self.connectionDelay = options.connectionDelay || 1000;
self.emit('connect', 'Connected to Papertrail at ' + self.host + ':' + self.port);
self.processBuffer();
}
};
//
//
// Inherit from `winston.Transport` so you can take advantage
// of the base functionality and `.handleExceptions()`.
//
util.inherits(Papertrail, winston.Transport);
//
// Define a getter so that `winston.transports.Papertrail`
// is available and thus backwards compatible.
//
winston.transports.Papertrail = Papertrail;
/**
* Papertrail.log
*
* @description Core logging method exposed to Winston. Metadata is optional.
*
* @param {String} level Level at which to log the message.
* @param {String} msg Message to log
* @param {String|object|Function} [meta] Optional metadata to attach
* @param {Function} callback
* @returns {*}
*/
Papertrail.prototype.log = function (level, msg, meta, callback) {
var self = this;
// make sure we handle when meta isn't provided
if (typeof(meta) === 'function' && !callback) {
callback = meta;
meta = false;
}
if (meta && typeof meta === 'object' && (Object.keys(meta).length === 0)
&& (!util.isError(meta))) {
meta = false;
}
// If the logging buffer is disabled, drop the message on the floor
if (!this.loggingEnabled) {
return callback(null, true);
}
var output = msg;
// If we don't have a string for the message,
// lets transform it before moving on
if (typeof(output) !== 'string') {
output = util.inspect(output, false, self.depth, self.colorize);
}
if (meta) {
if (typeof meta !== 'object') {
output += ' ' + meta;
}
else if (meta) {
if (this.inlineMeta) {
output += ' ' + util.inspect(meta, false, self.depth, self.colorize).replace(/[\n\t]\s*/gm, " ");
}
else {
output += '\n' + util.inspect(meta, false, self.depth, self.colorize);
}
}
}
this.sendMessage(this.hostname, this.program, level, output, callback);
};
/**
* Papertrail.sendMessage
*
* @description sending the message to the stream, or buffering if not connected
*
* @param {String} hostname Hostname of the source application.
* @param {String} program Name of the source application
* @param {String} level Log level of the message
* @param {String} message The message to deliver
* @param {Function} callback callback to be executed when the log has been written to the stream
*/
Papertrail.prototype.sendMessage = function (hostname, program, level, message, callback) {
var self = this,
lines = [],
msg = '',
gap = '';
// Only split if we actually have a message
if (message) {
lines = message.split('\n');
}
else {
lines = [''];
}
// If the incoming message has multiple lines, break them and format each
// line as its own message
for (var i = 0; i < lines.length; i++) {
// don't send extra message if our message ends with a newline
if ((lines[i].length === 0) && (i == lines.length - 1)) {
break;
}
if (i == 1) {
gap = ' ';
}
msg += self.producer.produce({
severity: self.levels[level] ? self.levels[level] : level,
host: hostname,
appName: program,
date: new Date(),
message: self.logFormat(self.colorize ? winston.config.colorize(level) : level, gap + lines[i])
}) + '\r\n';
}
if (this.stream && this.stream.writable) {
this.processBuffer();
this.stream.write(msg, callback);
}
else if (this.loggingEnabled && this.buffer.length < this.maxBufferSize) {
this.buffer += msg;
}
};
/**
* If we have anything buffered, try to write it to the stream if we can before we log new messages
*/
Papertrail.prototype.processBuffer = function() {
var self = this;
// Did we have buffered messages?
if (this.buffer.length <= 0) {
return;
}
// Is the stream writable?
if (!this.stream || !this.stream.writable) {
return;
}
this.stream.write(this.buffer, function() {
if (!self.buffer.length) {
self.stream.emit('empty');
}
});
this.buffer = '';
};
/**
* Papertrail.close
*
* @description closes the underlying TLS connection and disables automatic
* reconnection, allowing the process to exit
*/
Papertrail.prototype.close = function() {
var self = this;
self._shutdown = true;
if (self.stream) {
if (self.flushOnClose && self.buffer.length) {
self.stream.on('empty', function() {
// TODO: some kind of guard here to avoid infinite recursion?
self.close();
});
}
else {
self.stream.end();
}
}
// if there's no stream yet, that means we're still connecting
// lets wire a connect handler, and then invoke close again
else {
self.on('connect', function() {
self.close();
});
}
};
/**
* The goal here is to ignore connection errors by default without triggering an uncaughtException.
* You can still bind your own error handler as normal, but if you haven't overridden it, connection errors
* will be logged to the console by default.
*
* Notes: This is meant to fix usability issues #20, and #49
*
* @param err
* @private
*/
Papertrail.prototype._silentErrorEmitter = function(err) {
var count = this.listeners('error').length;
if (count > 0) {
// the goal here is to ensure someone is catching this event, instead of potentially
// causing the process to exit.
this.emit('error', err);
}
else {
console.error('Papertrail connection error: ', err);
}
};