forked from googleapis/google-cloud-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.js
More file actions
660 lines (614 loc) · 17.7 KB
/
log.js
File metadata and controls
660 lines (614 loc) · 17.7 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!
* @module logging/log
*/
'use strict';
var arrify = require('arrify');
var async = require('async');
var common = require('@google-cloud/common');
var extend = require('extend');
var is = require('is');
/**
* @type {module:logging/entry}
* @private
*/
var Entry = require('./entry.js');
/**
* @type {module:logging/metadata}
* @private
*/
var Metadata = require('./metadata.js');
/*! Developer Documentation
*
* @param {module:logging} logging - Parent Logging instance.
*/
/**
* A log is a named collection of entries, each entry representing a timestamped
* event. Logs can be produced by Google Cloud Platform services, by third-party
* services, or by your applications. For example, the log `apache-access` is
* produced by the Apache Web Server, but the log
* `compute.googleapis.com/activity_log` is produced by Google Compute Engine.
*
* @resource [Introduction to Logs]{@link https://cloud.google.com/logging/docs/basic-concepts#logs}
*
* @alias module:logging/log
* @constructor
*
* @param {string} name - Name of the log.
* @param {object=} options - Configuration object.
* @param {boolean} options.removeCircular - Replace circular references in
* logged objects with a string value, `[Circular]`. (Default: false)
*
* @example
* var log = logging.log('syslog');
*/
function Log(logging, name, options) {
options = options || {};
this.formattedName_ = Log.formatName_(logging.projectId, name);
this.removeCircular_ = options.removeCircular === true;
this.metadata_ = new Metadata(logging);
this.logging = logging;
this.name = this.formattedName_.split('/').pop();
}
/**
* Return an array of log entries with the desired severity assigned.
*
* @private
*
* @param {object|object[]} entries - Log entries.
* @param {string} severity - The desired severity level.
*/
Log.assignSeverityToEntries_ = function(entries, severity) {
return arrify(entries).map(function(entry) {
var metadata = extend(true, {}, entry.metadata, {
severity: severity
});
return extend(new Entry(), entry, {
metadata: metadata
});
});
};
/**
* Format the name of a log. A log's full name is in the format of
* 'projects/{projectId}/logs/{logName}'.
*
* @private
*
* @return {string}
*/
Log.formatName_ = function(projectId, name) {
var path = 'projects/' + projectId + '/logs/';
name = name.replace(path, '');
if (decodeURIComponent(name) === name) {
// The name has not been encoded yet.
name = encodeURIComponent(name);
}
return path + name;
};
/**
* Write a log entry with a severity of "ALERT".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.alert(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.alert(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.alert = function(entry, options, callback) {
this.write(Log.assignSeverityToEntries_(entry, 'ALERT'), options, callback);
};
/**
* Write a log entry with a severity of "CRITICAL".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.critical(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.critical(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.critical = function(entry, options, callback) {
var entries = Log.assignSeverityToEntries_(entry, 'CRITICAL');
this.write(entries, options, callback);
};
/**
* Write a log entry with a severity of "DEBUG".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.debug(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.debug(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.debug = function(entry, options, callback) {
this.write(Log.assignSeverityToEntries_(entry, 'DEBUG'), options, callback);
};
/**
* Delete the log.
*
* @resource [projects.logs.delete API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete}
*
* @param {object=} gaxOptions - Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this
* request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* log.delete(function(err, apiResponse) {
* if (!err) {
* // The log was deleted.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.delete().then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.delete = function(gaxOptions, callback) {
if (is.fn(gaxOptions)) {
callback = gaxOptions;
gaxOptions = {};
}
var reqOpts = {
logName: this.formattedName_
};
this.logging.request({
client: 'loggingServiceV2Client',
method: 'deleteLog',
reqOpts: reqOpts,
gaxOpts: gaxOptions
}, callback);
};
/**
* Write a log entry with a severity of "EMERGENCY".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.emergency(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.emergency(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.emergency = function(entry, options, callback) {
var entries = Log.assignSeverityToEntries_(entry, 'EMERGENCY');
this.write(entries, options, callback);
};
/**
* Create an entry object for this log.
*
* Note that using this method will not itself make any API requests. You will
* use the object returned in other API calls, such as
* {module:logging/log#write}.
*
* @resource [LogEntry JSON representation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry}
*
* @param {object=} metadata - See a
* [LogEntry Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry).
* @param {object|string} data - The data to use as the value for this log
* entry.
* @return {module:logging/entry}
*
* @example
* var metadata = {
* resource: {
* type: 'gce_instance',
* labels: {
* zone: 'global',
* instance_id: '3'
* }
* }
* };
*
* var entry = log.entry(metadata, {
* delegate: 'my_username'
* });
*
* entry.toJSON();
* // {
* // logName: 'projects/grape-spaceship-123/logs/syslog',
* // resource: {
* // type: 'gce_instance',
* // labels: {
* // zone: 'global',
* // instance_id: '3'
* // }
* // },
* // jsonPayload: {
* // delegate: 'my_username'
* // }
* // }
*/
Log.prototype.entry = function(metadata, data) {
if (!data) {
data = metadata;
metadata = {};
}
metadata = extend({}, metadata, {
logName: this.formattedName_
});
return this.logging.entry(metadata, data);
};
/**
* Write a log entry with a severity of "ERROR".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.error(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.error(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.error = function(entry, options, callback) {
this.write(Log.assignSeverityToEntries_(entry, 'ERROR'), options, callback);
};
/**
* This method is a wrapper around {module:logging#getEntries}, but with a
* filter specified to only return entries from this log.
*
* @resource [entries.list API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list}
*
* @param {object=} options - Filtering options.
* @param {boolean} options.autoPaginate - Have pagination handled
* automatically. Default: true.
* @param {string} options.filter - An
* [advanced logs filter](https://cloud.google.com/logging/docs/view/advanced_filters).
* An empty filter matches all log entries.
* @param {number} options.maxApiCalls - Maximum number of API calls to make.
* @param {number} options.maxResults - Maximum number of results to return.
* @param {string} options.orderBy - How the results should be sorted,
* `timestamp` (oldest first) and `timestamp desc` (newest first,
* **default**).
* @param {number} options.pageSize - Maximum number of logs to return.
* @param {string} options.pageToken - A previously-returned page token
* representing part of the larger set of results to view.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:logging/entry[]} callback.entries - Entries from this log.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* log.getEntries(function(err, entries) {
* // `entries` is an array of Stackdriver Logging entry objects.
* // See the `data` property to read the data from the entry.
* });
*
* //-
* // To control how many API requests are made and page through the results
* // manually, set `autoPaginate` to `false`.
* //-
* function callback(err, entries, nextQuery, apiResponse) {
* if (nextQuery) {
* // More results exist.
* log.getEntries(nextQuery, callback);
* }
* }
*
* log.getEntries({
* autoPaginate: false
* }, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.getEntries().then(function(data) {
* var entries = data[0];
* });
*/
Log.prototype.getEntries = function(options, callback) {
if (is.function(options)) {
callback = options;
options = {};
}
options = extend({
filter: 'logName="' + this.formattedName_ + '"'
}, options);
return this.logging.getEntries(options, callback);
};
/**
* This method is a wrapper around {module:logging#getEntriesStream}, but with a
* filter specified to only return {module:logging/entry} objects from this log.
*
* @param {object=} options - Configuration object. See
* {module:logging/log#getEntries} for a complete list of options.
* @return {stream}
*
* @example
* log.getEntriesStream()
* .on('error', console.error)
* .on('data', function(entry) {
* // `entry` is a Stackdriver Logging entry object.
* // See the `data` property to read the data from the entry.
* })
* .on('end', function() {
* // All entries retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* log.getEntriesStream()
* .on('data', function(entry) {
* this.end();
* });
*/
Log.prototype.getEntriesStream = function(options) {
options = extend({
filter: 'logName="' + this.formattedName_ + '"'
}, options);
return this.logging.getEntriesStream(options);
};
/**
* Write a log entry with a severity of "INFO".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.info(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.info(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.info = function(entry, options, callback) {
this.write(Log.assignSeverityToEntries_(entry, 'INFO'), options, callback);
};
/**
* Write a log entry with a severity of "NOTICE".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.notice(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.notice(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.notice = function(entry, options, callback) {
this.write(Log.assignSeverityToEntries_(entry, 'NOTICE'), options, callback);
};
/**
* Write a log entry with a severity of "WARNING".
*
* This is a simple wrapper around {module:logging/log#write}. All arguments are
* the same as documented there.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.warning(entry, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.warning(entry).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.warning = function(entry, options, callback) {
this.write(Log.assignSeverityToEntries_(entry, 'WARNING'), options, callback);
};
/**
* Write log entries to Stackdriver Logging.
*
* While you may write a single entry at a time, batching multiple entries
* together is preferred to avoid reaching the queries per second limit.
*
* @resource [entries.write API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write}
*
* @param {module:logging/entry|module:logging/entry[]} entry - A log entry, or
* array of entries, to write.
* @param {object=} options - Configuration object.
* @param {object} options.gaxOptions - Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {object[]} options.labels - Labels to set on the log.
* @param {object} options.resource - A default monitored resource for entries
* where one isn't specified.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* var entry = log.entry('gce_instance', {
* instance: 'my_instance'
* });
*
* log.write(entry, function(err, apiResponse) {
* if (!err) {
* // The log entry was written.
* }
* });
*
* //-
* // You may also pass multiple log entries to write.
* //-
* var secondEntry = log.entry('compute.googleapis.com', {
* user: 'my_username'
* });
*
* log.write([
* entry,
* secondEntry
* ], function(err, apiResponse) {
* if (!err) {
* // The log entries were written.
* }
* });
*
* //-
* // To save some steps, you can also pass in plain values as your entries.
* // Note, however, that you must provide a configuration object to specify the
* // resource.
* //-
* var entries = [
* {
* user: 'my_username'
* },
* {
* home: process.env.HOME
* }
* ];
*
* var options = {
* resource: 'compute.googleapis.com'
* };
*
* log.write(entries, options, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* log.write(entries).then(function(data) {
* var apiResponse = data[0];
* });
*/
Log.prototype.write = function(entry, options, callback) {
var self = this;
if (is.fn(options)) {
callback = options;
options = {};
}
this.decorateEntries_(arrify(entry), function(err, decoratedEntries) {
// Ignore errors (the API will speak up if it has an issue).
var reqOpts = extend({
logName: self.formattedName_,
entries: decoratedEntries
}, options);
delete reqOpts.gaxOptions;
self.logging.request({
client: 'loggingServiceV2Client',
method: 'writeLogEntries',
reqOpts: reqOpts,
gaxOpts: options.gaxOptions
}, callback);
});
};
/**
* All entries are passed through here to make sure this log is attached to the
* entry.
*
* @private
*
* @param {object} entry - An entry object.
*/
Log.prototype.decorateEntries_ = function(entries, callback) {
var self = this;
async.map(entries, function(entry, callback) {
if (!(entry instanceof Entry)) {
entry = self.entry(entry);
}
var decoratedEntry;
try {
decoratedEntry = entry.toJSON({
removeCircular: self.removeCircular_
});
} catch(e) {
callback(e);
return;
}
decoratedEntry.logName = self.formattedName_;
self.metadata_.assignDefaultResource(decoratedEntry, function(err, entry) {
// Ignore errors (the API will speak up if it has an issue).
callback(null, entry || decoratedEntry);
});
}, callback);
};
/*! Developer Documentation
*
* All async methods (except for streams) will return a Promise in the event
* that a callback is omitted.
*/
common.util.promisifyAll(Log, {
exclude: ['entry']
});
module.exports = Log;