forked from MauriceButler/bunyan-loggly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (59 loc) · 2.06 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
var loggly = require('node-loggly-bulk');
var stringifySafe = require('json-stringify-safe');
var noop = function () {};
function Bunyan2Loggly(logglyConfig, bufferLength, bufferTimeout, callback) {
if (!logglyConfig || !logglyConfig.token || !logglyConfig.subdomain) {
throw new Error('bunyan-loggly requires a config object with token and subdomain');
}
logglyConfig.json = true;
logglyConfig.isBulk = true;
this.logglyClient = loggly.createClient(logglyConfig);
this._buffer = [];
this.bufferLength = bufferLength || 1;
this.bufferTimeout = bufferTimeout;
this.callback = callback || noop;
}
Bunyan2Loggly.prototype.write = function (originalData) {
if (typeof originalData !== 'object') {
throw new Error('bunyan-loggly requires a raw stream. Please define the type as raw when setting up the bunyan stream.');
}
var data = originalData;
// loggly prefers timestamp over time
if (data.time) {
data = JSON.parse(stringifySafe(data, null, null, noop));
data.timestamp = data.time;
delete data.time;
}
this._buffer.push(data);
this._checkBuffer();
};
Bunyan2Loggly.prototype._processBuffer = function () {
var bunyan2Loggly = this;
clearTimeout(bunyan2Loggly._timeoutId);
var content = bunyan2Loggly._buffer.slice();
bunyan2Loggly._buffer = [];
for (var i = 0; i < content.length; i++) {
bunyan2Loggly.logglyClient.log(content[i], function (error, result) {
bunyan2Loggly.callback(error, result, content);
});
}
};
Bunyan2Loggly.prototype._checkBuffer = function () {
var bunyan2Loggly = this;
if (!this._buffer.length) {
return;
}
if (this._buffer.length >= this.bufferLength) {
return this._processBuffer();
}
if (this.bufferTimeout) {
clearTimeout(this._timeoutId);
this._timeoutId = setTimeout(
function () {
bunyan2Loggly._processBuffer();
},
this.bufferTimeout
);
}
};
module.exports = Bunyan2Loggly;