@webex/plugin-logger 3.12.0-webex-services-ready.4 → 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,7 +129,21 @@ 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() {
@@ -111,13 +154,14 @@ const Logger = WebexPlugin.extend({
111
154
  };
112
155
  },
113
156
  },
157
+ // Current indentation depth for buffered groups.
114
158
  groupLevel: {
115
159
  type: 'number',
116
160
  default() {
117
161
  return 0;
118
162
  },
119
163
  },
120
- // for when configured to use separate buffers
164
+ // SDK history and support-upload cursors. Used only when separateLogBuffers is true.
121
165
  sdkBuffer: {
122
166
  type: 'object',
123
167
  default() {
@@ -128,6 +172,7 @@ const Logger = WebexPlugin.extend({
128
172
  };
129
173
  },
130
174
  },
175
+ // Client history and support-upload cursors. Used only when separateLogBuffers is true.
131
176
  clientBuffer: {
132
177
  type: 'object',
133
178
  default() {
@@ -141,36 +186,96 @@ const Logger = WebexPlugin.extend({
141
186
  },
142
187
 
143
188
  /**
144
- * Ensures auth headers don't get printed in logs
145
- * @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.
146
219
  * @private
147
- * @memberof Logger
148
- * @returns {Array<mixed>}
220
+ * @returns {Object} Filtered arguments and metadata for this call.
149
221
  */
150
- filter(...args) {
151
- return args.map((arg) => {
152
- // WebexHttpError already ensures auth tokens don't get printed, so, no
153
- // 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.
154
231
  if (arg instanceof Error) {
155
- // karma logs won't print subclassed errors correctly, so we need
156
- // explicitly call their tostring methods.
157
232
  if (process.env.NODE_ENV === 'test' && inBrowser) {
158
233
  let ret = arg.toString();
159
234
 
160
235
  ret += 'BEGIN STACK';
161
236
  ret += arg.stack;
162
237
  ret += 'END STACK';
163
-
164
- return ret;
238
+ filteredArguments.push(ret);
239
+ } else {
240
+ filteredArguments.push(arg);
165
241
  }
166
242
 
167
- return arg;
243
+ return;
168
244
  }
169
245
 
170
- 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;
171
256
 
172
- 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)));
173
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;
174
279
  },
175
280
 
176
281
  /**
@@ -362,15 +467,16 @@ const Logger = WebexPlugin.extend({
362
467
  * @param {string} level level to create (info, error, warn, etc.)
363
468
  * @param {string} impl the level to use when writing to console
364
469
  * @param {string} type type of log, SDK or client
365
- * @param {bool} neverPrint function never prints to console
366
- * @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.
367
473
  * @instance
368
474
  * @memberof Logger
369
475
  * @private
370
476
  * @memberof Logger
371
477
  * @returns {function} logger method with specified params
372
478
  */
373
- function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer = false) {
479
+ function makeLoggerMethod(level, impl, type, {neverPrint = false, alwaysBuffer = false} = {}) {
374
480
  // Much of the complexity in the following function is due to a test-mode-only
375
481
  // helper
376
482
  return function wrappedConsoleMethod(...args) {
@@ -402,8 +508,9 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
402
508
  return;
403
509
  }
404
510
 
405
- const filtered = [clientName, ...this.filter(...args)];
406
- const stringified = filtered.map((item) => {
511
+ const {filteredArguments, metadata} = this._filterLogArguments(...args);
512
+ const filtered = [clientName, ...filteredArguments];
513
+ const formatted = filtered.map((item) => {
407
514
  if (item instanceof Error) {
408
515
  return item.toString();
409
516
  }
@@ -435,26 +542,38 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
435
542
  });
436
543
 
437
544
  if (shouldPrint) {
438
- // when logging an object in browsers, we tend to get a dynamic
439
- // reference, thus going back to look at the logged value doesn't
440
- // necessarily show the state at log time, thus we print the stringified
441
- // value.
442
- 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;
443
547
 
444
548
  /* istanbul ignore if */
445
549
  if (process.env.NODE_ENV === 'test' && has(this, 'webex.internal.device.url')) {
446
550
  toPrint.unshift(this.webex.internal.device.url.slice(-3));
447
551
  }
448
- // eslint-disable-next-line no-console
449
- 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);
450
562
  }
451
563
 
452
564
  if (shouldBuffer) {
453
565
  const logDate = new Date();
454
566
 
455
- stringified.unshift(logDate.toISOString());
456
- stringified.unshift('| '.repeat(this.groupLevel));
457
- 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);
458
577
  if (bufferRef.buffer.length > historyLength) {
459
578
  // we've gone over the buffer limit, trim it down
460
579
  const deleteCount = bufferRef.buffer.length - historyLength;
@@ -472,8 +591,13 @@ function makeLoggerMethod(level, impl, type, neverPrint = false, alwaysBuffer =
472
591
  bufferRef.lastSubmitted = 0;
473
592
  }
474
593
  }
475
- if (level === 'group') this.groupLevel += 1;
476
- 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));
477
601
  }
478
602
  } catch (reason) {
479
603
  if (!neverPrint) {
@@ -502,19 +626,13 @@ levels.forEach((level) => {
502
626
  Logger.prototype[level] = makeLoggerMethod(level, impl, LOG_TYPES.SDK);
503
627
  });
504
628
 
505
- Logger.prototype.client_logToBuffer = makeLoggerMethod(
506
- levels.info,
507
- levels.info,
508
- LOG_TYPES.CLIENT,
509
- true,
510
- true
511
- );
512
- Logger.prototype.logToBuffer = makeLoggerMethod(
513
- levels.info,
514
- levels.info,
515
- LOG_TYPES.SDK,
516
- true,
517
- true
518
- );
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
+ });
519
637
 
520
638
  export default Logger;