@webex/plugin-logger 3.12.0 → 3.13.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/logger.js CHANGED
@@ -2,6 +2,14 @@
2
2
  * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
3
3
  */
4
4
 
5
+ /**
6
+ * plugin-logger emits 'log:record' synchronously after it retains an entry.
7
+ * Use webex.logger.on('log:record', listener) to receive future records.
8
+ * Use webex.logger.off('log:record', listener) to remove the same listener.
9
+ * Listeners must not throw or log back into this logger synchronously.
10
+ * Nested logging can deliver newer records first to later listeners.
11
+ * A thrown error can stop delivery to later listeners.
12
+ */
5
13
  import {inBrowser, patterns} from '@webex/common';
6
14
  import {WebexPlugin} from '@webex/webex-core';
7
15
  import {cloneDeep, has, isArray, isObject, isString} from 'lodash';
@@ -34,7 +42,6 @@ const LOG_TYPES = {
34
42
  };
35
43
 
36
44
  const SDK_LOG_TYPE_NAME = 'wx-js-sdk';
37
-
38
45
  const authTokenKeyPattern = /[Aa]uthorization/;
39
46
 
40
47
  /**
@@ -79,6 +86,28 @@ function walkAndFilter(object, visited = []) {
79
86
  return object;
80
87
  }
81
88
 
89
+ /**
90
+ * Build a record from one retained entry. Live events and history use this function.
91
+ * @param {Array<mixed>} entry Formatted text with capture fields stored as named properties.
92
+ * @returns {Object} A record that shares the caller-owned metadata values.
93
+ */
94
+ function _createLogRecord(entry) {
95
+ const record = {
96
+ sequence: entry.sequence,
97
+ timestamp: entry.timestamp,
98
+ level: entry.level,
99
+ source: entry.source,
100
+ body: entry.join(','),
101
+ };
102
+
103
+ if (entry.metadata) {
104
+ record.eventName = entry.metadata.eventName;
105
+ record.attributes = entry.metadata.attributes;
106
+ }
107
+
108
+ return record;
109
+ }
110
+
82
111
  /**
83
112
  * @class
84
113
  */
@@ -100,74 +129,155 @@ const Logger = WebexPlugin.extend({
100
129
  },
101
130
  },
102
131
  session: {
103
- // for when configured to use single buffer
132
+ // Shared attributes for this instance. Each retained record copies their current values.
133
+ logAttributes: {type: 'object'},
134
+ // Keep the counter inside an object so increments do not emit Ampersand change events.
135
+ recordState: {
136
+ type: 'object',
137
+ /**
138
+ * Create empty state for this logger instance.
139
+ * @returns {Object} The shared SDK and client sequence counter.
140
+ */
141
+ default() {
142
+ return {
143
+ // Last sequence assigned. Buffer trimming does not reset it.
144
+ lastSequence: 0,
145
+ };
146
+ },
147
+ },
148
+ // Retained history and support-upload cursors when SDK and client logs share one buffer.
104
149
  buffer: {
105
150
  type: 'object',
106
151
  default() {
107
152
  return {
108
153
  buffer: [],
109
154
  nextIndex: 0,
155
+ lastSubmitted: 0,
110
156
  };
111
157
  },
112
158
  },
159
+ // Current indentation depth for buffered groups.
113
160
  groupLevel: {
114
161
  type: 'number',
115
162
  default() {
116
163
  return 0;
117
164
  },
118
165
  },
119
- // for when configured to use separate buffers
166
+ // SDK history and support-upload cursors. Used only when separateLogBuffers is true.
120
167
  sdkBuffer: {
121
168
  type: 'object',
122
169
  default() {
123
170
  return {
124
171
  buffer: [],
125
172
  nextIndex: 0,
173
+ lastSubmitted: 0,
126
174
  };
127
175
  },
128
176
  },
177
+ // Client history and support-upload cursors. Used only when separateLogBuffers is true.
129
178
  clientBuffer: {
130
179
  type: 'object',
131
180
  default() {
132
181
  return {
133
182
  buffer: [],
134
183
  nextIndex: 0,
184
+ lastSubmitted: 0,
135
185
  };
136
186
  },
137
187
  },
138
188
  },
139
189
 
140
190
  /**
141
- * Ensures auth headers don't get printed in logs
142
- * @param {Array<mixed>} args
191
+ * Read retained entries in sequence order without changing support-upload cursors.
192
+ * Use on('log:record', listener) for future records. Consumers must leave metadata unchanged.
193
+ * @returns {Array} Records built from the retained entries.
194
+ */
195
+ getRecords() {
196
+ const sdkBuffer = this.config.separateLogBuffers ? this.sdkBuffer.buffer : this.buffer.buffer;
197
+ const clientBuffer = this.config.separateLogBuffers ? this.clientBuffer.buffer : [];
198
+ const records = [];
199
+ let sdkIndex = 0;
200
+ let clientIndex = 0;
201
+
202
+ while (sdkIndex < sdkBuffer.length || clientIndex < clientBuffer.length) {
203
+ const sdkEntry = sdkBuffer[sdkIndex];
204
+ const clientEntry = clientBuffer[clientIndex];
205
+
206
+ if (sdkEntry && (!clientEntry || sdkEntry.sequence < clientEntry.sequence)) {
207
+ records.push(_createLogRecord(sdkEntry));
208
+ sdkIndex += 1;
209
+ } else {
210
+ records.push(_createLogRecord(clientEntry));
211
+ clientIndex += 1;
212
+ }
213
+ }
214
+
215
+ return records;
216
+ },
217
+
218
+ /**
219
+ * Filter message data and extract configured metadata in one argument pass.
220
+ * @param {Array<mixed>} args Message arguments.
143
221
  * @private
144
- * @memberof Logger
145
- * @returns {Array<mixed>}
222
+ * @returns {Object} Filtered arguments and metadata for this call.
146
223
  */
147
- filter(...args) {
148
- return args.map((arg) => {
149
- // WebexHttpError already ensures auth tokens don't get printed, so, no
150
- // need to alter it here.
224
+ _filterLogArguments(...args) {
225
+ const {metadataField} = this.config;
226
+ const filteredArguments = [];
227
+ let metadata;
228
+
229
+ args.forEach((argument) => {
230
+ let arg = argument;
231
+
232
+ // WebexHttpError already excludes auth tokens. Keep the existing Error handling.
151
233
  if (arg instanceof Error) {
152
- // karma logs won't print subclassed errors correctly, so we need
153
- // explicitly call their tostring methods.
154
234
  if (process.env.NODE_ENV === 'test' && inBrowser) {
155
235
  let ret = arg.toString();
156
236
 
157
237
  ret += 'BEGIN STACK';
158
238
  ret += arg.stack;
159
239
  ret += 'END STACK';
160
-
161
- return ret;
240
+ filteredArguments.push(ret);
241
+ } else {
242
+ filteredArguments.push(arg);
162
243
  }
163
244
 
164
- return arg;
245
+ return;
165
246
  }
166
247
 
167
- arg = cloneDeep(arg);
248
+ if (
249
+ metadataField &&
250
+ arg !== null &&
251
+ typeof arg === 'object' &&
252
+ !Array.isArray(arg) &&
253
+ Object.prototype.hasOwnProperty.call(arg, metadataField)
254
+ ) {
255
+ // Callers supply safe metadata; text redaction does not sanitize it.
256
+ // Copy and redact only the remaining message fields.
257
+ const {[metadataField]: recordMetadata, ...messageFields} = arg;
258
+
259
+ metadata = recordMetadata;
260
+ if (Object.keys(messageFields).length === 0) {
261
+ return;
262
+ }
263
+ arg = messageFields;
264
+ }
168
265
 
169
- return walkAndFilter(arg);
266
+ filteredArguments.push(walkAndFilter(cloneDeep(arg)));
170
267
  });
268
+
269
+ return {filteredArguments, metadata};
270
+ },
271
+
272
+ /**
273
+ * Ensures auth headers don't get printed in logs
274
+ * @param {Array<mixed>} args
275
+ * @private
276
+ * @memberof Logger
277
+ * @returns {Array<mixed>}
278
+ */
279
+ filter(...args) {
280
+ return this._filterLogArguments(...args).filteredArguments;
171
281
  },
172
282
 
173
283
  /**
@@ -322,6 +432,34 @@ const Logger = WebexPlugin.extend({
322
432
 
323
433
  return buffer.join('\n');
324
434
  },
435
+
436
+ /**
437
+ * Update the last submitted index in the buffers to the current nextIndex
438
+ *
439
+ * @returns {void}
440
+ */
441
+ updateLastSubmittedIndex() {
442
+ if (this.config.separateLogBuffers) {
443
+ this.clientBuffer.lastSubmitted = this.clientBuffer.nextIndex;
444
+ this.sdkBuffer.lastSubmitted = this.sdkBuffer.nextIndex;
445
+ } else {
446
+ this.buffer.lastSubmitted = this.buffer.nextIndex;
447
+ }
448
+ },
449
+
450
+ /**
451
+ * Reset the nextIndex in the buffers to the last successful upload index, effectively including any logs since the last successful upload in the next upload
452
+ *
453
+ * @returns {void}
454
+ */
455
+ resetBufferToLastSuccessfulUpload() {
456
+ if (this.config.separateLogBuffers) {
457
+ this.clientBuffer.nextIndex = this.clientBuffer.lastSubmitted;
458
+ this.sdkBuffer.nextIndex = this.sdkBuffer.lastSubmitted;
459
+ } else {
460
+ this.buffer.nextIndex = this.buffer.lastSubmitted;
461
+ }
462
+ },
325
463
  });
326
464
 
327
465
  /**
@@ -331,15 +469,16 @@ const Logger = WebexPlugin.extend({
331
469
  * @param {string} level level to create (info, error, warn, etc.)
332
470
  * @param {string} impl the level to use when writing to console
333
471
  * @param {string} type type of log, SDK or client
334
- * @param {bool} neverPrint function never prints to console
335
- * @param {bool} alwaysBuffer function always logs to log buffer
472
+ * @param {Object} options - Internal formatting/buffering options.
473
+ * @param {boolean} [options.neverPrint=false] - Never print to the console.
474
+ * @param {boolean} [options.alwaysBuffer=false] - Retain regardless of the configured level.
336
475
  * @instance
337
476
  * @memberof Logger
338
477
  * @private
339
478
  * @memberof Logger
340
479
  * @returns {function} logger method with specified params
341
480
  */
342
- function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer = false) {
481
+ function makeLoggerMethod(level, impl, type, {neverPrint = false, alwaysBuffer = false} = {}) {
343
482
  // Much of the complexity in the following function is due to a test-mode-only
344
483
  // helper
345
484
  return function wrappedConsoleMethod(...args) {
@@ -371,8 +510,9 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
371
510
  return;
372
511
  }
373
512
 
374
- const filtered = [clientName, ...this.filter(...args)];
375
- const stringified = filtered.map((item) => {
513
+ const {filteredArguments, metadata} = this._filterLogArguments(...args);
514
+ const filtered = [clientName, ...filteredArguments];
515
+ const formatted = filtered.map((item) => {
376
516
  if (item instanceof Error) {
377
517
  return item.toString();
378
518
  }
@@ -404,26 +544,44 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
404
544
  });
405
545
 
406
546
  if (shouldPrint) {
407
- // when logging an object in browsers, we tend to get a dynamic
408
- // reference, thus going back to look at the logged value doesn't
409
- // necessarily show the state at log time, thus we print the stringified
410
- // value.
411
- const toPrint = inBrowser ? stringified : filtered;
547
+ // Print formatted browser values so later object changes do not change the displayed log.
548
+ const toPrint = inBrowser ? formatted : filtered;
412
549
 
413
550
  /* istanbul ignore if */
414
551
  if (process.env.NODE_ENV === 'test' && has(this, 'webex.internal.device.url')) {
415
552
  toPrint.unshift(this.webex.internal.device.url.slice(-3));
416
553
  }
417
- // eslint-disable-next-line no-console
418
- console[impl](...toPrint);
554
+ // Bypass host capture only when this call will also enter the SDK buffer.
555
+ const consoleMethodName = (shouldBuffer && this.config.consoleMethods?.[impl]) || impl;
556
+ /* eslint-disable no-console */
557
+ const consoleMethod =
558
+ typeof console[consoleMethodName] === 'function'
559
+ ? console[consoleMethodName]
560
+ : console[impl];
561
+ /* eslint-enable no-console */
562
+
563
+ consoleMethod.apply(console, toPrint);
419
564
  }
420
565
 
421
566
  if (shouldBuffer) {
422
567
  const logDate = new Date();
423
568
 
424
- stringified.unshift(logDate.toISOString());
425
- stringified.unshift('| '.repeat(this.groupLevel));
426
- bufferRef.buffer.push(stringified);
569
+ formatted.unshift(logDate.toISOString());
570
+ formatted.unshift('| '.repeat(this.groupLevel));
571
+ this.recordState.lastSequence += 1;
572
+ // Named fields retain record data without changing the support-log array positions.
573
+ formatted.sequence = this.recordState.lastSequence;
574
+ formatted.timestamp = logDate.getTime();
575
+ formatted.level = level;
576
+ formatted.source = metadata?.source || logType;
577
+ formatted.metadata = metadata;
578
+ if (this.logAttributes) {
579
+ formatted.metadata = {
580
+ ...metadata,
581
+ attributes: {...this.logAttributes, ...metadata?.attributes},
582
+ };
583
+ }
584
+ bufferRef.buffer.push(formatted);
427
585
  if (bufferRef.buffer.length > historyLength) {
428
586
  // we've gone over the buffer limit, trim it down
429
587
  const deleteCount = bufferRef.buffer.length - historyLength;
@@ -435,9 +593,19 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
435
593
  if (bufferRef.nextIndex < 0) {
436
594
  bufferRef.nextIndex = 0;
437
595
  }
596
+
597
+ bufferRef.lastSubmitted -= deleteCount;
598
+ if (bufferRef.lastSubmitted < 0) {
599
+ bufferRef.lastSubmitted = 0;
600
+ }
438
601
  }
439
- if (level === 'group') this.groupLevel += 1;
440
- if (level === 'groupEnd' && this.groupLevel > 0) this.groupLevel -= 1;
602
+ if (level === 'group') {
603
+ this.groupLevel += 1;
604
+ }
605
+ if (level === 'groupEnd' && this.groupLevel > 0) {
606
+ this.groupLevel -= 1;
607
+ }
608
+ this.trigger('log:record', _createLogRecord(formatted));
441
609
  }
442
610
  } catch (reason) {
443
611
  if (!neverPrint) {
@@ -466,19 +634,13 @@ levels.forEach((level) => {
466
634
  Logger.prototype[level] = makeLoggerMethod(level, impl, LOG_TYPES.SDK);
467
635
  });
468
636
 
469
- Logger.prototype.client_logToBuffer = makeLoggerMethod(
470
- levels.info,
471
- levels.info,
472
- LOG_TYPES.CLIENT,
473
- true,
474
- true
475
- );
476
- Logger.prototype.logToBuffer = makeLoggerMethod(
477
- levels.info,
478
- levels.info,
479
- LOG_TYPES.SDK,
480
- true,
481
- true
482
- );
637
+ Logger.prototype.client_logToBuffer = makeLoggerMethod('info', 'info', LOG_TYPES.CLIENT, {
638
+ neverPrint: true,
639
+ alwaysBuffer: true,
640
+ });
641
+ Logger.prototype.logToBuffer = makeLoggerMethod('info', 'info', LOG_TYPES.SDK, {
642
+ neverPrint: true,
643
+ alwaysBuffer: true,
644
+ });
483
645
 
484
646
  export default Logger;