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

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,153 @@ const Logger = WebexPlugin.extend({
100
129
  },
101
130
  },
102
131
  session: {
103
- // for when configured to use single buffer
132
+ // Keep the counter inside an object so increments do not emit Ampersand change events.
133
+ recordState: {
134
+ type: 'object',
135
+ /**
136
+ * Create empty state for this logger instance.
137
+ * @returns {Object} The shared SDK and client sequence counter.
138
+ */
139
+ default() {
140
+ return {
141
+ // Last sequence assigned. Buffer trimming does not reset it.
142
+ lastSequence: 0,
143
+ };
144
+ },
145
+ },
146
+ // Retained history and support-upload cursors when SDK and client logs share one buffer.
104
147
  buffer: {
105
148
  type: 'object',
106
149
  default() {
107
150
  return {
108
151
  buffer: [],
109
152
  nextIndex: 0,
153
+ lastSubmitted: 0,
110
154
  };
111
155
  },
112
156
  },
157
+ // Current indentation depth for buffered groups.
113
158
  groupLevel: {
114
159
  type: 'number',
115
160
  default() {
116
161
  return 0;
117
162
  },
118
163
  },
119
- // for when configured to use separate buffers
164
+ // SDK history and support-upload cursors. Used only when separateLogBuffers is true.
120
165
  sdkBuffer: {
121
166
  type: 'object',
122
167
  default() {
123
168
  return {
124
169
  buffer: [],
125
170
  nextIndex: 0,
171
+ lastSubmitted: 0,
126
172
  };
127
173
  },
128
174
  },
175
+ // Client history and support-upload cursors. Used only when separateLogBuffers is true.
129
176
  clientBuffer: {
130
177
  type: 'object',
131
178
  default() {
132
179
  return {
133
180
  buffer: [],
134
181
  nextIndex: 0,
182
+ lastSubmitted: 0,
135
183
  };
136
184
  },
137
185
  },
138
186
  },
139
187
 
140
188
  /**
141
- * Ensures auth headers don't get printed in logs
142
- * @param {Array<mixed>} args
189
+ * Read retained entries in sequence order without changing support-upload cursors.
190
+ * Use on('log:record', listener) for future records. Consumers must leave metadata unchanged.
191
+ * @returns {Array} Records built from the retained entries.
192
+ */
193
+ getRecords() {
194
+ const sdkBuffer = this.config.separateLogBuffers ? this.sdkBuffer.buffer : this.buffer.buffer;
195
+ const clientBuffer = this.config.separateLogBuffers ? this.clientBuffer.buffer : [];
196
+ const records = [];
197
+ let sdkIndex = 0;
198
+ let clientIndex = 0;
199
+
200
+ while (sdkIndex < sdkBuffer.length || clientIndex < clientBuffer.length) {
201
+ const sdkEntry = sdkBuffer[sdkIndex];
202
+ const clientEntry = clientBuffer[clientIndex];
203
+
204
+ if (sdkEntry && (!clientEntry || sdkEntry.sequence < clientEntry.sequence)) {
205
+ records.push(_createLogRecord(sdkEntry));
206
+ sdkIndex += 1;
207
+ } else {
208
+ records.push(_createLogRecord(clientEntry));
209
+ clientIndex += 1;
210
+ }
211
+ }
212
+
213
+ return records;
214
+ },
215
+
216
+ /**
217
+ * Filter message data and extract configured metadata in one argument pass.
218
+ * @param {Array<mixed>} args Message arguments.
143
219
  * @private
144
- * @memberof Logger
145
- * @returns {Array<mixed>}
220
+ * @returns {Object} Filtered arguments and metadata for this call.
146
221
  */
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.
222
+ _filterLogArguments(...args) {
223
+ const {metadataField} = this.config;
224
+ const filteredArguments = [];
225
+ let metadata;
226
+
227
+ args.forEach((argument) => {
228
+ let arg = argument;
229
+
230
+ // WebexHttpError already excludes auth tokens. Keep the existing Error handling.
151
231
  if (arg instanceof Error) {
152
- // karma logs won't print subclassed errors correctly, so we need
153
- // explicitly call their tostring methods.
154
232
  if (process.env.NODE_ENV === 'test' && inBrowser) {
155
233
  let ret = arg.toString();
156
234
 
157
235
  ret += 'BEGIN STACK';
158
236
  ret += arg.stack;
159
237
  ret += 'END STACK';
160
-
161
- return ret;
238
+ filteredArguments.push(ret);
239
+ } else {
240
+ filteredArguments.push(arg);
162
241
  }
163
242
 
164
- return arg;
243
+ return;
165
244
  }
166
245
 
167
- arg = cloneDeep(arg);
246
+ if (
247
+ metadataField &&
248
+ arg !== null &&
249
+ typeof arg === 'object' &&
250
+ !Array.isArray(arg) &&
251
+ Object.prototype.hasOwnProperty.call(arg, metadataField)
252
+ ) {
253
+ // Callers supply safe metadata; text redaction does not sanitize it.
254
+ // Copy and redact only the remaining message fields.
255
+ const {[metadataField]: recordMetadata, ...messageFields} = arg;
168
256
 
169
- return walkAndFilter(arg);
257
+ metadata = recordMetadata;
258
+ if (Object.keys(messageFields).length === 0) {
259
+ return;
260
+ }
261
+ arg = messageFields;
262
+ }
263
+
264
+ filteredArguments.push(walkAndFilter(cloneDeep(arg)));
170
265
  });
266
+
267
+ return {filteredArguments, metadata};
268
+ },
269
+
270
+ /**
271
+ * Ensures auth headers don't get printed in logs
272
+ * @param {Array<mixed>} args
273
+ * @private
274
+ * @memberof Logger
275
+ * @returns {Array<mixed>}
276
+ */
277
+ filter(...args) {
278
+ return this._filterLogArguments(...args).filteredArguments;
171
279
  },
172
280
 
173
281
  /**
@@ -322,6 +430,34 @@ const Logger = WebexPlugin.extend({
322
430
 
323
431
  return buffer.join('\n');
324
432
  },
433
+
434
+ /**
435
+ * Update the last submitted index in the buffers to the current nextIndex
436
+ *
437
+ * @returns {void}
438
+ */
439
+ updateLastSubmittedIndex() {
440
+ if (this.config.separateLogBuffers) {
441
+ this.clientBuffer.lastSubmitted = this.clientBuffer.nextIndex;
442
+ this.sdkBuffer.lastSubmitted = this.sdkBuffer.nextIndex;
443
+ } else {
444
+ this.buffer.lastSubmitted = this.buffer.nextIndex;
445
+ }
446
+ },
447
+
448
+ /**
449
+ * 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
450
+ *
451
+ * @returns {void}
452
+ */
453
+ resetBufferToLastSuccessfulUpload() {
454
+ if (this.config.separateLogBuffers) {
455
+ this.clientBuffer.nextIndex = this.clientBuffer.lastSubmitted;
456
+ this.sdkBuffer.nextIndex = this.sdkBuffer.lastSubmitted;
457
+ } else {
458
+ this.buffer.nextIndex = this.buffer.lastSubmitted;
459
+ }
460
+ },
325
461
  });
326
462
 
327
463
  /**
@@ -331,15 +467,16 @@ const Logger = WebexPlugin.extend({
331
467
  * @param {string} level level to create (info, error, warn, etc.)
332
468
  * @param {string} impl the level to use when writing to console
333
469
  * @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
470
+ * @param {Object} options - Internal formatting/buffering options.
471
+ * @param {boolean} [options.neverPrint=false] - Never print to the console.
472
+ * @param {boolean} [options.alwaysBuffer=false] - Retain regardless of the configured level.
336
473
  * @instance
337
474
  * @memberof Logger
338
475
  * @private
339
476
  * @memberof Logger
340
477
  * @returns {function} logger method with specified params
341
478
  */
342
- function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer = false) {
479
+ function makeLoggerMethod(level, impl, type, {neverPrint = false, alwaysBuffer = false} = {}) {
343
480
  // Much of the complexity in the following function is due to a test-mode-only
344
481
  // helper
345
482
  return function wrappedConsoleMethod(...args) {
@@ -371,8 +508,9 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
371
508
  return;
372
509
  }
373
510
 
374
- const filtered = [clientName, ...this.filter(...args)];
375
- const stringified = filtered.map((item) => {
511
+ const {filteredArguments, metadata} = this._filterLogArguments(...args);
512
+ const filtered = [clientName, ...filteredArguments];
513
+ const formatted = filtered.map((item) => {
376
514
  if (item instanceof Error) {
377
515
  return item.toString();
378
516
  }
@@ -404,26 +542,38 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
404
542
  });
405
543
 
406
544
  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;
545
+ // Print formatted browser values so later object changes do not change the displayed log.
546
+ const toPrint = inBrowser ? formatted : filtered;
412
547
 
413
548
  /* istanbul ignore if */
414
549
  if (process.env.NODE_ENV === 'test' && has(this, 'webex.internal.device.url')) {
415
550
  toPrint.unshift(this.webex.internal.device.url.slice(-3));
416
551
  }
417
- // eslint-disable-next-line no-console
418
- console[impl](...toPrint);
552
+ // Bypass host capture only when this call will also enter the SDK buffer.
553
+ const consoleMethodName = (shouldBuffer && this.config.consoleMethods?.[impl]) || impl;
554
+ /* eslint-disable no-console */
555
+ const consoleMethod =
556
+ typeof console[consoleMethodName] === 'function'
557
+ ? console[consoleMethodName]
558
+ : console[impl];
559
+ /* eslint-enable no-console */
560
+
561
+ consoleMethod.apply(console, toPrint);
419
562
  }
420
563
 
421
564
  if (shouldBuffer) {
422
565
  const logDate = new Date();
423
566
 
424
- stringified.unshift(logDate.toISOString());
425
- stringified.unshift('| '.repeat(this.groupLevel));
426
- bufferRef.buffer.push(stringified);
567
+ formatted.unshift(logDate.toISOString());
568
+ formatted.unshift('| '.repeat(this.groupLevel));
569
+ this.recordState.lastSequence += 1;
570
+ // Named fields retain record data without changing the support-log array positions.
571
+ formatted.sequence = this.recordState.lastSequence;
572
+ formatted.timestamp = logDate.getTime();
573
+ formatted.level = level;
574
+ formatted.source = metadata?.source || logType;
575
+ formatted.metadata = metadata;
576
+ bufferRef.buffer.push(formatted);
427
577
  if (bufferRef.buffer.length > historyLength) {
428
578
  // we've gone over the buffer limit, trim it down
429
579
  const deleteCount = bufferRef.buffer.length - historyLength;
@@ -435,9 +585,19 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
435
585
  if (bufferRef.nextIndex < 0) {
436
586
  bufferRef.nextIndex = 0;
437
587
  }
588
+
589
+ bufferRef.lastSubmitted -= deleteCount;
590
+ if (bufferRef.lastSubmitted < 0) {
591
+ bufferRef.lastSubmitted = 0;
592
+ }
438
593
  }
439
- if (level === 'group') this.groupLevel += 1;
440
- if (level === 'groupEnd' && this.groupLevel > 0) this.groupLevel -= 1;
594
+ if (level === 'group') {
595
+ this.groupLevel += 1;
596
+ }
597
+ if (level === 'groupEnd' && this.groupLevel > 0) {
598
+ this.groupLevel -= 1;
599
+ }
600
+ this.trigger('log:record', _createLogRecord(formatted));
441
601
  }
442
602
  } catch (reason) {
443
603
  if (!neverPrint) {
@@ -466,19 +626,13 @@ levels.forEach((level) => {
466
626
  Logger.prototype[level] = makeLoggerMethod(level, impl, LOG_TYPES.SDK);
467
627
  });
468
628
 
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
- );
629
+ Logger.prototype.client_logToBuffer = makeLoggerMethod('info', 'info', LOG_TYPES.CLIENT, {
630
+ neverPrint: true,
631
+ alwaysBuffer: true,
632
+ });
633
+ Logger.prototype.logToBuffer = makeLoggerMethod('info', 'info', LOG_TYPES.SDK, {
634
+ neverPrint: true,
635
+ alwaysBuffer: true,
636
+ });
483
637
 
484
638
  export default Logger;