All files / tao-telemetry/src ConsoleSink.js

100% Statements 14/14
100% Branches 18/18
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                            11x 11x 11x 11x                       19x     19x 2x   19x 19x 19x 19x 19x     19x 1x        
/** @typedef {import('./Tracer').TraceRecord} TraceRecord */
 
/**
 * Streams signals to a console-like logger as they occur, indented by causal
 * depth — the live-logging successor to `TaoLogger`'s full-wildcard idiom.
 *
 * @export
 * @class ConsoleSink
 */
export default class ConsoleSink {
  /**
   * Creates an instance of ConsoleSink.
   * @param {Object} [opts]
   * @param {{ info: function }} [opts.logger=console] - console-like target
   * @param {boolean} [opts.showData=false] - also log each record's captured
   *        data on a second line
   * @param {number} [opts.limit=10000] - cap on the signalId → depth map used
   *        for indentation (FIFO eviction; a child of an evicted parent logs
   *        at root depth)
   * @memberof ConsoleSink
   */
  constructor({ logger = console, showData = false, limit = 10000 } = {}) {
    this._logger = logger;
    this._showData = showData;
    this._limit = limit;
    this._depths = new Map();
  }
 
  /**
   * Sink interface: log one signal as it occurs, indented beneath its cause
   * (with its producing phase when present).
   *
   * @param {TraceRecord} record
   * @memberof ConsoleSink
   */
  signal(record) {
    const depth =
      record.parentId && this._depths.has(record.parentId)
        ? this._depths.get(record.parentId) + 1
        : 0;
    if (this._depths.size >= this._limit) {
      this._depths.delete(this._depths.keys().next().value);
    }
    this._depths.set(record.signalId, depth);
    const indent = '  '.repeat(depth);
    const link = depth > 0 ? '↳ ' : '';
    const via = record.via ? ` ·${record.via}` : '';
    this._logger.info(
      `${indent}${link}☯{${record.t}, ${record.a}, ${record.o}}${via}`,
    );
    if (this._showData && typeof record.data !== 'undefined') {
      this._logger.info(`${indent}  `, record.data);
    }
  }
}