All files / lib/internal/util debuglog.js

100% Statements 77/77
100% Branches 15/15
100% Functions 5/5
100% Lines 77/77

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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4357x 4357x 4357x 27x 27x 27x 27x 27x 27x 4357x 1x 1x 1x 19x 19x 3x 3x 3x 3x 3x 19x 1x 19912x 19912x 19912x 14724x 19x 19x 19x 108x 108x 108x 108x 19x 14724x 14705x 14705x 14724x 19912x 19912x 1x 1x 1x 1x 1x 56711x 56711x 56711x 6954438x 19912x 19912x 19912x 19912x 6954438x 6954438x 56711x 56711x 1x 1x 1x 1x 1x  
'use strict';
 
const {
  RegExp,
} = primordials;
 
const { inspect, format, formatWithOptions } = require('internal/util/inspect');
 
// `debugs` is deliberately initialized to undefined so any call to
// debuglog() before initializeDebugEnv() is called will throw.
let debugs;
 
let debugEnvRegex = /^$/;
 
// `debugEnv` is initial value of process.env.NODE_DEBUG
function initializeDebugEnv(debugEnv) {
  debugs = {};
  if (debugEnv) {
    debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
      .replace(/\*/g, '.*')
      .replace(/,/g, '$|^')
      .toUpperCase();
    debugEnvRegex = new RegExp(`^${debugEnv}$`, 'i');
  }
}
 
// Emits warning when user sets
// NODE_DEBUG=http or NODE_DEBUG=http2.
function emitWarningIfNeeded(set) {
  if ('HTTP' === set || 'HTTP2' === set) {
    process.emitWarning('Setting the NODE_DEBUG environment variable ' +
      'to \'' + set.toLowerCase() + '\' can expose sensitive ' +
      'data (such as passwords, tokens and authentication headers) ' +
      'in the resulting log.');
  }
}
 
function debuglogImpl(set) {
  set = set.toUpperCase();
  if (debugs[set] === undefined) {
    if (debugEnvRegex.test(set)) {
      const pid = process.pid;
      emitWarningIfNeeded(set);
      debugs[set] = function debug(...args) {
        const colors = process.stderr.hasColors && process.stderr.hasColors();
        const msg = formatWithOptions({ colors }, ...args);
        const coloredPID = inspect(pid, { colors });
        process.stderr.write(format('%s %s: %s\n', set, coloredPID, msg));
      };
    } else {
      debugs[set] = null;
    }
  }
  return debugs[set];
}
 
// debuglogImpl depends on process.pid and process.env.NODE_DEBUG,
// so it needs to be called lazily in top scopes of internal modules
// that may be loaded before these run time states are allowed to
// be accessed.
function debuglog(set) {
  let debug;
  return function(...args) {
    if (debug === undefined) {
      // Only invokes debuglogImpl() when the debug function is
      // called for the first time.
      debug = debuglogImpl(set);
    }
    if (debug !== null)
      debug(...args);
  };
}
 
module.exports = {
  debuglog,
  initializeDebugEnv
};