forked from winstonjs/winston-loggly
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathwinston-loggly.js
executable file
·360 lines (312 loc) · 8.62 KB
/
winston-loggly.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
/*
* loggly.js: Transport for logginh to remote Loggly API
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*
*/
var cloneDeep = require('lodash.clonedeep'),
loggly = require('node-loggly-bulk'),
util = require('util'),
winston = require('winston'),
Transport = require('winston-transport'),
Stream = require('stream').Stream;
//
// Remark: This should be at a higher level.
//
var code = /\u001b\[(\d+(;\d+)*)?m/g;
var timerFunctionForProcessExit = null;
//
// ### function Loggly (options)
// #### @options {Object} Options for this instance.
// Constructor function for the Loggly transport object responsible
// for persisting log messages and metadata to Loggly; 'LaaS'.
//
var Loggly = (exports.Loggly = function(options) {
options = options || {};
//
// Small amount of backwards compatibility with 0.x.x
//
if (options.inputToken && !options.token) {
options.token = options.inputToken;
}
Transport.call(this, options);
if (!options.subdomain) {
throw new Error('Loggly Subdomain is required');
} else if (!options || !options.token) {
throw new Error('Loggly Customer token is required.');
}
this.name = 'loggly';
var tags = options.tags || options.tag || options.id;
if (tags && !Array.isArray(tags)) {
tags = [tags];
}
this.client = loggly.createClient({
subdomain: options.subdomain,
json: options.json || false, //TODO: should be false
proxy: options.proxy || null,
token: options.token,
tags: tags,
isBulk: options.isBulk || false,
bufferOptions: options.bufferOptions || {
size: 500,
retriesInMilliSeconds: 30 * 1000
},
networkErrorsOnConsole: options.networkErrorsOnConsole || false
});
this.timestamp = options.timestamp === false ? false : true;
this.stripColors = options.stripColors || false;
});
//
// Helper function to call process.exit() after waiting
// 10 seconds.
//
var flushLogsAndExit = (exports.flushLogsAndExit = function() {
if (timerFunctionForProcessExit === null) {
timerFunctionForProcessExit = setInterval(function() {
process.exit();
}, 10000);
}
});
//
// Inherit from `winston.Transport`.
//
util.inherits(Loggly, Transport);
//
// Define a getter so that `winston.transports.Loggly`
// is available and thus backwards compatible.
//
winston.transports.Loggly = Loggly;
winston.transports.flushLogsAndExit = flushLogsAndExit;
//
// Expose the name of this Transport on the prototype
//
Loggly.prototype.name = 'loggly';
const validateMetadata = meta => {
if (meta == null) {
return {};
} else if (typeof meta !== 'object') {
return { metadata: meta };
} else {
return cloneDeep(meta);
}
};
//
// ### function log (meta, callback)
// #### @meta {Object} event data
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
Loggly.prototype.log = function(meta, callback) {
const data = validateMetadata(meta);
if (this.silent) {
return callback(null, true);
}
if (this.timestamp && !data.timestamp) {
data.timestamp = new Date().toISOString();
}
if (this.stripColors) {
data.message = ('' + data.message).replace(code, '');
}
const splats = data[Symbol.for('splat')];
if (splats && splats.length > 0) {
let details =
typeof splats[0] === 'object' ? splats.slice(1, splats.length) : splats; //ignore the first object, it's already included in root
if (splats[0].details !== undefined) {
//overwrites the original details prop, so we need to include it
details = [{ details: splats[0].details }, ...details];
}
if (details.length) data.details = details;
}
const self = this;
//
// Helper function for responded to logging.
//
function logged(err, result) {
self.emit('logged');
if (err) {
console.error('Loggly Error:', err);
}
try {
callback && callback(err, result);
} catch(ex){
return String(ex);
}
}
const result =
data && data.tags
? this.client.log(data, data.tags, logged)
: this.client.log(data, logged);
return result;
};
//
// ### function stream (options)
// #### @options {Object} Set stream options
// Returns a log stream.
//
Loggly.prototype.stream = function(maybeOptions) {
var self = this,
options = maybeOptions || {},
stream = new Stream(),
last,
start = options.start,
row = 0;
if (start === -1) {
start = null;
}
if (start == null) {
last = new Date(0).toISOString();
}
stream.destroy = function() {
this.destroyed = true;
};
// Unfortunately, we
// need to poll here.
(function check() {
self.query(
{
from: last || 'NOW-1DAY',
until: 'NOW'
},
function(err, results) {
if (stream.destroyed) return;
if (err) {
stream.emit('error', err);
return setTimeout(check, 2000);
}
var result = results[results.length - 1];
if (result && result.timestamp) {
if (last == null) {
last = result.timestamp;
return;
}
last = result.timestamp;
} else {
return;
}
results.forEach(function(log) {
if (start == null || row > start) {
stream.emit('log', log);
}
row++;
});
setTimeout(check, 2000);
}
);
})();
return stream;
};
//
// ### function query (options)
// #### @options {Object} Set stream options
// #### @callback {function} Callback
// Query the transport.
//
Loggly.prototype.query = function(options, callback) {
var self = this,
context = this.extractContext(options);
options = this.loglify(options);
options = this.extend(options, context);
this.client.search(options).run(function(err, logs) {
return err ? callback(err) : callback(null, self.sanitizeLogs(logs));
});
};
//
// ### function formatQuery (query)
// #### @query {string|Object} Query to format
// Formats the specified `query` Object (or string) to conform
// with the underlying implementation of this transport.
//
Loggly.prototype.formatQuery = function(query) {
return query;
};
//
// ### function formatResults (results, options)
// #### @results {Object|Array} Results returned from `.query`.
// #### @options {Object} **Optional** Formatting options
// Formats the specified `results` with the given `options` according
// to the implementation of this transport.
//
Loggly.prototype.formatResults = function(results, _options) {
return results;
};
//
// ### function extractContext (obj)
// #### @obj {Object} Options has to extract Loggly 'context' properties from
// Returns a separate object containing all Loggly 'context properties in
// the object supplied and removes those properties from the original object.
// [See Loggly Search API](http://wiki.loggly.com/retrieve_events#optional)
//
Loggly.prototype.extractContext = function(obj) {
var context = {};
[
'start',
'from',
'until',
'order',
'callback',
'size',
'format',
'fields'
].forEach(function(key) {
if (obj[key]) {
context[key] = obj[key];
delete obj[key];
}
});
context = this.normalizeQuery(context);
context.from = context.from.toISOString();
context.until = context.until.toISOString();
context.from = context.from || '-1d';
context.until = context.until || 'now';
context.size = context.size || 50;
return context;
};
//
// ### function loglify (obj)
// #### @obj {Object} Search query to convert into an `AND` loggly query.
// Creates an `AND` joined loggly query for the specified object
//
// e.g. `{ foo: 1, bar: 2 }` => `json.foo:1 AND json.bar:2`
//
Loggly.prototype.loglify = function(obj) {
var opts = [];
Object.keys(obj).forEach(function(key) {
if (
key !== 'query' &&
key !== 'fields' &&
key !== 'start' &&
key !== 'rows' &&
key !== 'limit' &&
key !== 'from' &&
key !== 'until'
) {
if (key == 'tag') {
opts.push(key + ':' + obj[key]);
} else {
opts.push('json.' + key + ':' + obj[key]);
}
}
});
if (obj.query) {
opts.unshift(obj.query);
}
return { query: opts.join(' AND ') };
};
//
// ### function sanitizeLogs (logs)
// #### @logs {Object} Data returned from Loggly to sanitize
// Sanitizes the log information returned from Loggly so that
// users cannot gain access to critical information such as:
//
// 1. IP Addresses
// 2. Input names
// 3. Input IDs
//
Loggly.prototype.sanitizeLogs = function(logs) {
return logs;
};
Loggly.prototype.extend = function(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
};