Introduce options to the logger function.

@param {Function} fn Calback function.
@param {Object} options Properties to introduce on fn.
@returns {Function} The passed function
@public
545639
function introduce(fn, options) {
  var has = Object.prototype.hasOwnProperty;

  for (var key in options) {
    if (has.call(options, key)) {
      fn[key] = options[key];
    }
  }

  return fn;
}
1127339
function ConsoleLogger(options) {
	EventEmitter.call(this);
	this.options = options || {};
	// allow use to customize if they want the label or not
	this.prefix = this.options.prefix === undefined ? true : this.options.prefix;
	this.showcr = this.options.showcr === undefined ? true : this.options.showcr;
	this.showtab = this.options.showtab === undefined ? true : this.options.showtab;
	this.colorize = this.options.colorize === undefined ? checkColorize() : this.options.colorize;
	this.logPrepend = this.options.logPrepend;
	chalk.enabled = !!this.colorize;

	// if we are logging from a cluster worker, prepend the process PID
	// istanbul ignore if
	if (cluster.isWorker) {
		if (chalk.enabled) {
			this.logPrepend = chalk.black.inverse(String(process.pid)) + grey(' |');
		} else {
			this.logPrepend = process.pid + ' |';
		}
	}
	this.remapLevels();
}
49343
function LoggerConfiguration(logger) {
  /**
   * Override default logger instance with the provided logger
   * @public
   * @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function
   */
  function useLogger(loggerOrFactoryFunction) {
    cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');

    if (typeof(loggerOrFactoryFunction) === 'function') {
      logger = loggerOrFactoryFunction();
    }
    else {
      logger = loggerOrFactoryFunction;
    }
  };

  /**
   * Gets the default or overridden logger
   * @public
   */
  function getParams() {
    return { logger };
  }

  return {
    /**
     * Gets the target for a configurator function to run on
     * @public
     */
    getTarget: function() {
      return { useLogger: useLogger };
    },
    getParams: getParams
  };
}
699832
function log( func, msg ){
  var logline = '['+func+'] '+msg;

  if ( logInfo ) {
    if ( logInfoStr == '' ) {
      console.log( logline );      
    } else if ( logInfoStr.indexOf( func ) >= 0 ) { 
      console.log( logline );
    }
  }

  // send log to event broker
  if ( loggerEvents ) { 
    var logBroker = getEventBroker('log');
    logBroker.cleanupQueue( 1000 );
    logBroker.queueEvent( { text: logline, channel:'log' } );
  }
  
}
391008
function(opts) {
	if (!opts) { opts = {}; }

	this._opts = opts;
	this._logRequestQueue = [];
	this._backends = new Map();

	// Set up regular expressions so that logTypes can be registered with
	// backends, and so that logData can be routed to the right backends.
	// Default: matches empty string only
	this._testAllRE = new RegExp(/^$/);

	this._samplers = [];
	this._samplersRE = new RegExp(/^$/);
	this._samplersCache = new Map();
}
905480
function doOnce(fn) {
    var called = false;
    return function() {
      if (called) throw new Error("Callback already called.");
      called = true;
      fn.apply(root, arguments);
    };
  }
333241
function addTypeFunction (typeName, funcName, func) {
  if (!stringValue(typeName)) {
    throw new Error('Invalid "typeName" argument, must be String')
  } else if (!_.isFunction(func) && !stringValue(func)) {
    throw new Error('Invalid func argument, must be function')
  }
  _.set(this.backing, [ typeName, `_${funcName}` ], func)
  return this
}
79082
function pr_autolog(options) {

    function espectRewrite(filepath, outpath, template) {
      var autologret = require(template);
      autologret(filepath, outpath);
    }

    function insertReturnLog(source, endLine) {
      var sourceRet;
      // Insert ending log at return statement.
      sourceRet = source.replace(/(\s|;)return(\s|;)/g, "$1" + endLine + "return$2");

      // Remove any ending log that added twice.
      while(sourceRet.indexOf(endLine + endLine) !== -1) {
        sourceRet = sourceRet.replace(endLine + endLine, endLine);
      }
      return sourceRet;
    }

    function insertEnterAndLeaveLog(item, node, functionName) {
      var fnoutLine = 'var DEBOUT="debuguy,"' +
        ' + (new Date()).getTime() + ",' +
        item.substring(0, item.lastIndexOf('.')) + '.' +
        functionName + '@' +
        node.loc.start.line + '";console.log(DEBOUT + ",ENTER," + Date.now());';
      var fnEndLine = 'console.log(DEBOUT + ",LEAVE," + Date.now());';

      var startLine = node.getSource().indexOf('{') + 1;
      var endLine = node.getSource().lastIndexOf('}');
      var source = node.getSource().substr(0, startLine) + fnoutLine +
                   node.getSource().substr(startLine, endLine - startLine) + fnEndLine +
                   node.getSource().substr(endLine);
      source = insertReturnLog(source, fnEndLine);
      return source;
    }

    function insertEnterLog(item, node, functionName) {
      var fnoutLine = '\nconsole.log("debuguy,"' +
        ' + (new Date()).getTime() + ",' +
        item.substring(0, item.lastIndexOf('.')) + '.' +
        functionName + '@' +
        node.loc.start.line + '");';
      var startLine = node.getSource().indexOf('{') + 1;
      var source = node.getSource().substr(0, startLine) + fnoutLine +
                   node.getSource().substr(startLine);
      return source;
    }

    this.traverse(options, function insertLog (dir, item, out) {
      if (options.xEspect) {
        var templatefile = __dirname + '/autolog.esp.js';
        if ('string' === typeof options.xEspect) {
          templatefile = options.xEspect;
        }
        espectRewrite(dir + item, out + item, templatefile);
        return;
      }
      fs.readFile(dir + item, function(err, data) {
        console.log('adding log ' + dir + item);

        if (err) {
          console.log(err);
          console.log(data);
          return;
        }

        var text = data.toString();
        var output;

        try {
          output = esprimaTraversal(text, {loc:true})
            .traverse(function (node) {
            if (node.type === 'ArrowFunctionExpression' ||
                node.type === 'FunctionDeclaration' ||
                node.type === 'FunctionExpression') {
              // Get the name of the function
              var functionName = 'anonymous';
              if (node.id) {
                functionName = node.id.name;
              } else if (node.parent) {
                switch (node.parent.type) {
                case 'VariableDeclarator':
                  functionName = node.parent.id.name;
                  break;
                case 'Property':
                  functionName = node.parent.key.name;
                  break;
                case 'AssignmentExpression':
                  if (node.parent.left.type === 'MemberExpression') {
                    functionName = node.parent.left.property.name ||
                                   node.parent.left.property.value;
                  }
                  else if (node.parent.left.type === 'Identifier') {
                    functionName = node.parent.left.name;
                  }
                  break;
                }
              }
              // Build the console log output
              var source;
              if (options.callStackGraph) {
                source = insertEnterAndLeaveLog(item, node, functionName);
              } else {
                source = insertEnterLog(item, node, functionName);
              }
              node.updateSource(source);
            }
          });

          fs.writeFile(out + item, output, function(err) {
            if (err) {
              console.log(err);
            } else {
              console.log(out + item + ' was saved!');
            }
          });
        }
        catch (e) {
          console.log('parsing failed: ' + dir + item);
          console.log(e);
        }
      });
    });
  }
506237
function networkIdleCallback(fn, options = {timeout: 0}) {
  // Call the function immediately if required features are absent
  if (
    !('MessageChannel' in window) ||
    !('serviceWorker' in navigator) ||
    !navigator.serviceWorker.controller
  ) {
    DOMContentLoad.then(() => fn({didTimeout: false}));
    return;
  }

  const messageChannel = new MessageChannel();
  navigator.serviceWorker.controller
      .postMessage(
          'NETWORK_IDLE_ENQUIRY',
          [messageChannel.port2],
      );

  const timeoutId = setTimeout(() => {
    const cbToPop = networkIdleCallback.__callbacks__
        .find(cb => cb.id === timeoutId);

    networkIdleCallback.__popCallback__(cbToPop, true);
  }, options.timeout);

  networkIdleCallback.__callbacks__.push({
    id: timeoutId,
    fn,
    timeout: options.timeout,
  });

  messageChannel.port1.addEventListener('message', handleMessage);
  messageChannel.port1.start();
}
426700
function(logger) {
			if (typeof logger != "object"
				|| typeof logger.info != "function"
				|| typeof logger.debug != "function"
				|| typeof logger.warning != "function"
				|| typeof logger.error != "function"
			) {
				throw new Error("Logger is not valid. It should implement at least the functions: info, debug, warning, error.");
			}
			_private.oLog = logger;
		}
1264852
function add(opts, fn) {
    // Argument shuffling.
    if (!fn && typeof opts === 'function') {
      fn = opts;
      opts = undefined;
    }
    // Default options.
    opts = opts || {};
    opts.interval = opts.interval || 15 * 1000;
    opts.jitter = opts.jitter || 0.2;
    // Flag for stopping repeating interval.
    var stopFlag = false;
    // Recursive function.
    function rec() {
      // Start a new promise.
      return Promise.fromNode(function(cb) {
        // Apply jitter to interval to get next timeout duration.
        var duration = applyJitter(opts.jitter, opts.interval);
        // Init a timeout.
        setTimeout(function() {
          // Run handler function.
          return $q.try(fn)
          // Handle errors.
          .catch(function(err) {
            return errorHandler(err);
          })
          // Resolve promise.
          .nodeify(cb);
        }, duration);
      })
      // Recurse unless top flag has been set.
      .then(function() {
        if (!stopFlag) {
          return rec();
        }
      });
    }
    // Hold onto promise returned by recursive function so caller can wait on it.
    var prm = rec();
    // Return micro api so called can turn it off and wait for it to finish.
    var api = {
      fn: fn,
      stop: function() {
        // Tell recursive function to stop.
        stopFlag = true;
        // Return promise.
        return prm;
      }
    };
    // Add api to list of apis.
    fns.push(api);
    // Return api.
    return api;
  }
491411
function registerLoggingCallbacks(obj) {
  	var i,
  	    l,
  	    key,
  	    callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"];

  	function registerLoggingCallback(key) {
  		var loggingCallback = function loggingCallback(callback) {
  			if (objectType(callback) !== "function") {
  				throw new Error("QUnit logging methods require a callback function as their first parameters.");
  			}

  			config.callbacks[key].push(callback);
  		};

  		return loggingCallback;
  	}

  	for (i = 0, l = callbackNames.length; i < l; i++) {
  		key = callbackNames[i];

  		// Initialize key collection of logging callback
  		if (objectType(config.callbacks[key]) === "undefined") {
  			config.callbacks[key] = [];
  		}

  		obj[key] = registerLoggingCallback(key);
  	}
  }
285306
function logArr(arr) {

  if(arguments.length > 1) {
    if(!suppressWarnings) console.warn("'logArr' only supports 1 parameter. Converting to regular 'log'.");
    log(Array.prototype.slice.call(arguments));
    return;
  }

  if(! _.isArray(arr)) {
    if(!suppressWarnings) console.warn("'logArr' used, but first argument was not an array. Converting to regular 'log'.");
    log(arr);
    return;
  }
  log.apply(null, arr)
}
459888
function Logger() {
  /**
   * Write a simple log
   * @param {String|Object} message Message of body
   * @param {...*} [params] format the message body
   */
  this.log = function (message, params) {
    if (this.level() > 1) return;
    if (arguments.length > 1) message = String.prototype.format.apply(message, Array.prototype.slice.call(arguments, 1));
    message = this._prepareMessage('LOG', message);
    console.log(message);
    this._logToFile(message);
  };

  /**
   * Write a warning log
   * @param {String|Object} message Message of body
   * @param {...*} [params] format the message body
   */
  this.warn = function (message, params) {
    if (this.level() > 2) return;
    if (arguments.length > 1) message = String.prototype.format.apply(message, Array.prototype.slice.call(arguments, 1));
    message = this._prepareMessage('WARNING', message);
    console.warn(message);
    this._logToFile(message);
  };

  /**
   * Write a debug log
   * @param {String|Object} message Message of body
   * @param {...*} [params] format the message body
   */
  this.debug = function (message, params) {
    if (this.level() > 0) return;
    if (arguments.length > 1) message = String.prototype.format.apply(message, Array.prototype.slice.call(arguments, 1));
    message = this._prepareMessage('DEBUG', message);
    console.log(message);
    this._logToFile(message);
  };


  /**
   * Write an error message
   * @param {String|Object} message Message of body
   * @param {...*} [params] format the message body
   */
  this.error = function (message, params) {
    if (this.level() > 3) return;
    if (arguments.length > 1) message = String.prototype.format.apply(message, Array.prototype.slice.call(arguments, 1));
    message = this._prepareMessage('ERROR', message);
    console.error(message);
    this._logToFile(message);
  };


  /**
   * Prepares message
   * @param type What kind of message will be prepared
   * @param message What is the message
   * @returns {String}
   * @private
   */
  this._prepareMessage = function (type, message) {
    var simple = {
      type: this.colorType(type),
      message: typeof message == 'string' ? message : os.EOL + "{0 j 4}".format(message),
      var: defaults
    };
    switch (this.get('type')) {
      case 'simple':
        return this.get('simple').format(simple);
      case 'withFile':
        return this.get('withFile').format(Object.assign(simple, this._getActiveFunction()));
      default:
        var now = new Date();
        var date = this.get('dateFormat').format({
          year: now.getFullYear(),
          month: now.getMonth() + 1,
          day: now.getDate()
        });
        var time = this.get('timeFormat').format({
          hour: now.getHours(),
          minute: now.getMinutes(),
          second: now.getSeconds()
        });
        return (this.get(this.get('type')) || "").format(Object.assign(simple, {
          date: date,
          time: time
        }, this._getActiveFunction()));
    }
  };

  /**
   * Logs to file
   * @param message
   * @private
   */
  this._logToFile = function (message) {
    var now = new Date();
    var date = this.get('fileDateFormat').format({
      year: now.getFullYear(),
      month: now.getMonth() + 1,
      day: now.getDate()
    });
    var location = path.resolve(process.cwd(), this.get('dir'), this.get('fileFormat').format({date: date}));
    fs.appendFile(location, (message + os.EOL).replace(/\x1B\[\d+m/g, ''), function() {});
  };


  /**
   * Detect recording level
   * @returns {number}
   */
  this.level = function () {
    switch (this.get('level')) {
      case 'DEBUG':
        return 0;
      case 'LOG':
        return 1;
      case 'WARN':
        return 2;
      case 'ERROR':
        return 3;
      default:
        return 0;
    }
  };

  /**
   * Colored type
   * @returns {String}
   */
  this.colorType = function (type) {
    switch (type) {
      case 'DEBUG':
        return type.yellow;
      case 'LOG':
        return type.magenta;
      case 'WARN':
        return type.cyan;
      case 'ERROR':
        return type.red;
      default:
        return type;
    }
  };


  /**
   * Changes a default setting
   * @param {String} setting
   * @param {*} value
   * @return {String}
   */
  this.set = function (setting, value) {
    return defaults[setting] = value
  };


  /**
   * Gets a default setting
   * @param {String} setting
   * @return {String}
   */
  this.get = function (setting) {
    return defaults[setting]
  };


  /**
   * Finds file name that executing
   * @param {Number} [at] Stack position
   * @returns {{file: String, line: String}}
   * @private
   */
  this._getActiveFunction = function (at) {
    var temp = {};
    var stackTraceLimit = Error.stackTraceLimit;
    var prepareStackTrace = Error.prepareStackTrace;
    Error.stackTraceLimit = Infinity;

    Error.prepareStackTrace = function (dummyObject, v8StackTrace) {
      return v8StackTrace
    };
    Error.captureStackTrace(temp);

    var stack = temp.stack[at || 3];
    Error.prepareStackTrace = prepareStackTrace;
    Error.stackTraceLimit = stackTraceLimit;

    var file = stack["getEvalOrigin"]().split(/\\|\//).pop().blue;
    var line = stack["getLineNumber"]().toString().magenta;
    return {file: file, line: line};
  };

  /**
   * Check's logging directory's existence, if not then creates
   */
  this.checkDirectory = function () {
    var location = (path.resolve(process.cwd(), this.get('dir')));
    var dirs = location.split(path.sep), root = "";

    while (dirs.length > 0) {
      var dir = dirs.shift();
      if (dir === "") root = path.sep;
      if (!fs.existsSync(root + dir)) fs.mkdirSync(root + dir);
      root += dir + path.sep;
    }
  };

  this.checkDirectory();
}
1283519
function ReservoirBackend(options) {
    if (!(this instanceof ReservoirBackend)) {
        return new ReservoirBackend(options);
    }

    BaseBackend.call(this);

    this.backend = options.backend;
    assert(
        typeof this.backend === 'object' &&
        typeof this.backend.logMany === 'function',
        'options.backend must be object with `logMany` method'
    );

    this.size = options.size || 100;
    assert(
        typeof this.size === 'number' &&
        this.size >= 5 && this.size < 1000000000,
        'options.size must be number 5 >= n > 1000000000'
    );

    this.rangeRand = options.rangeRand || ReservoirBackend.rangeRand;
    assert(
        typeof this.rangeRand === 'function',
        'options.rangeRand must be function'
    );

    this.flushInterval = options.flushInterval || 50;
    assert(
        typeof this.flushInterval === 'number' &&
        this.flushInterval > 1 && this.flushInterval < 1000000,
        'options.flushInterval must be number 1 > n > 1000000'
    );

    this.timers = options.timers || timers;
    assert(
        typeof this.timers === 'object' &&
        typeof this.timers.setTimeout === 'function',
        'options.timers must be object with setTimeout function'
    );

    this.now = options.now || Date.now;
    assert(
        typeof this.now === 'function',
        'options.now must be function'
    );

    if (
        options.statsd &&
        typeof options.statsd.timing === 'function' &&
        typeof options.statsd.increment === 'function'
    ) {
        this.statsd = options.statsd;
    } else {
        this.statsd = {
            increment: noop,
            timing: noop
        };
    }

    this.clusterStatsd = options.clusterStatsd || null;

    this.timer = null;
    this.count = 0;
    this.records = [];
    this.dropCount = {};
    this.logCount = {};
    this.samplingDecision = null;
}
1066017
function makeLogger(level, method) {
	// The logger function to return takes a variable number of arguments
	// and formats like console.log
	function logger() {
		var args = [].slice.call(arguments);
		var format = level.toUpperCase() + ': (api-client) ' + args.shift();
		var logArgs = [format].concat(args);

		return console[method].apply(console, logArgs);
	}

	return (level === 'warn' || level === 'error' || level === 'info')
		? logger
		: function() {};
}
270102
def setLoggingFromOptions(options):
    
    #We can now set up the logging info.
    if options.logLevel is not None:
        setLogLevel(options.logLevel) #Use log level, unless flags are set..

    if options.logOff:
        setLogLevel("OFF")
    elif options.logInfo:
        setLogLevel("INFO")
    elif options.logDebug:
        setLogLevel("DEBUG")

    logger.info("Logging set at level: %s" % logLevelString)

    if options.logFile is not None:
        addLoggingFileHandler(options.logFile, options.logRotating)

    logger.info("Logging to file: %s" % options.logFile)