Helper for log handlers to evaluate / interpolate logger arguments.

@return {{ level: string, metadata: object, message: string }}
545268
function evaluateLogRowArgs(logArgs) {
  var name = logArgs[0];
  var logLevel = logArgs[1];
  var message = null;
  var obj = null;

  var firstArg = logArgs[2];

  if (!firstArg) {
    throw new Error('Invalid logArgs. At least one argument to log must be given.');
  }

  // resolve first argument if it is message or metadata
  if (_.isString(firstArg)) {
    message = util.format.apply(util.format, _.slice(logArgs, 2, logArgs.length));
  } else if (_.isFunction(firstArg)) {
    var firstArgFunctionResult = firstArg();
    if (_.isString(firstArgFunctionResult)) {
      message = firstArgFunctionResult;
    } else {
      obj = firstArgFunctionResult;
    }
  } else {
    obj = firstArg;
  }

  // if first argument was object, second argument defines the message
  // and if second argument is function it evaluates to message or params
  // are passed to util.format
  var secondArg = logArgs[3];

  if (!message && secondArg) {
    if (_.isFunction(secondArg)) {
      message = secondArg();
    } else {
      message = util.format.apply(util.format, _.slice(logArgs, 3, logArgs.length));
    }
  }

  return {
    name: name,
    level: logLevel,
    metadata: obj,
    message: message
  };
}
560750
function(msg){
		var logs = document.getElementById("logs");
		logs.innerHTML += Funcs.util.getTimeStamp() + ": " + msg + "\n";
	}
984763
function exposeAPI(log){
    return {
        emerg: log(_loglevel.EMERGENCY),
        emergency: log(_loglevel.EMERGENCY),

        alert: log(_loglevel.ALERT),

        crit: log(_loglevel.CRITICAL),
        critical: log(_loglevel.CRITICAL),

        error: log(_loglevel.ERROR),
        err: log(_loglevel.ERROR),

        warning: log(_loglevel.WARNING),
        warn: log(_loglevel.WARNING),

        notice: log(_loglevel.NOTICE),

        log: log(_loglevel.INFO),
        info: log(_loglevel.INFO),

        debug: log(_loglevel.DEBUG)
    };
}
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();
}
573034
function logHeaders(logger, headers) {
	return _.each(_.keys(headers), function (key) {
		logger.info(key + ': ' + headers[key]);
	});
}
1060936
def getCustomLogger(name, logLevel, logFormat='%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'):
  '''
  
  '''
  assert isinstance(logFormat, basestring), ("logFormat must be a string but is %r" % logFormat)
  assert isinstance(logLevel, basestring), ("logLevel must be a string but is %r" % logLevel)
  assert isinstance(name, basestring), ("name must be a string but is %r" % name)

  validLogLevels = ['CRITICAL', 'DEBUG', 'ERROR', 'INFO', 'WARNING']

  if not logLevel:
    logLevel = 'DEBUG'

  # If they don't specify a valid log level, err on the side of verbosity
  if logLevel.upper() not in validLogLevels:
    logLevel = 'DEBUG'

  numericLevel = getattr(logging, logLevel.upper(), None)
  if not isinstance(numericLevel, int):
    raise ValueError("Invalid log level: %s" % logLevel)

  logging.basicConfig(level=numericLevel, format=logFormat)
  logger = logging.getLogger(name)
  return logger
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() {};
}
189162
function customLogEvent(level) {

  // options should contain the appenders and handlers to override the
  // global ones defined in errorAppenders, and errorHandlers.
  // Used by Canadarm.localWatch to wrap local appender calls.
  return function (message, exception, data, settings) {

    // If we are are below the current Canadarm.loggingLevel we
    // should not do anything with the passed information.  Return
    // as if nothing happened.
    if (Canadarm.levelOrder.indexOf(level) < Canadarm.levelOrder.indexOf(Canadarm.loggingLevel)) {
      return;
    }

    var options = settings || {},
      attrs = gatherErrors(level, exception, message, data, options.appenders);
    pushErrors(attrs, options.handlers);
  };
}
623074
function (msg) {
            console.log("Runtime.evaluate");
            var result = eval(msg.params.expression);
            MessageBroker.respond(msg, {
                result: JSON.stringify(result) // TODO: in original protocol this is an object handle
            });
        }
1083681
function consoleHandler(logData) {
    'use strict';
    var consoleArgs = logData.hasOwnProperty('args') ? logData.args : logData.hasOwnProperty('logEntry') ? [logData.logEntry] : arguments;

    switch (logData.level) {
        case messageLevel.ERROR:
            origConErr.apply(console, consoleArgs);
            break;
        case messageLevel.WARN:
            origConWarn.apply(console, consoleArgs);
            break;
        case messageLevel.INFO:
            origConInfo.apply(console, consoleArgs);
            break;
        default:
            throw new Error('Invalid log level defined');
    }
}
785691
def log_handler(level: str, message: str) -> None:
    """"""
    message = 'JS: ' + str(message)
    if level == 'error':
        logger.error(message)
    elif level == 'warn':
        logger.warning(message)
    elif level == 'info':
        logger.info(message)
    elif level == 'debug':
        logger.debug(message)
654893
function log() {
  var args = NS ? [chalk.bold.gray(NS)] : []
  for(var i=0; i<arguments.length; i++) {
    var arg = arguments[i];
    args.push(chalk.cyan( typeof arg === "object" ? JSON.stringify(arg) : arg ))

    // adds a separator
    if(i < arguments.length-1) args.push(chalk.gray("|"));
  }
  if(testLog)   testLog(args);
  else          console.log.apply(null, args)
}
759034
def log_config(log_level: Union[str, int]) -> dict:
    
    if isinstance(log_level, int):
        # to match django
        log_level = {3: 'DEBUG', 2: 'INFO'}.get(log_level, 'WARNING')
    assert log_level in {'DEBUG', 'INFO', 'WARNING', 'ERROR'}, 'wrong log level %s' % log_level
    return {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'default': {'format': '%(message)s'},
            'indent': {'format': '    %(message)s'},
        },
        'handlers': {
            'default': {
                'level': log_level,
                'class': 'grablib.common.ClickHandler',
                'formatter': 'default'
            },
            'progress': {
                'level': log_level,
                'class': 'grablib.common.ProgressHandler',
                'formatter': 'indent'
            },
        },
        'loggers': {
            main_logger.name: {
                'handlers': ['default'],
                'level': log_level,
                'propagate': False,
            },
            progress_logger.name: {
                'handlers': ['progress'],
                'level': log_level,
                'propagate': False,
            },
        },
    }
841792
function _getLogger(level) {
        if (isNaN(level)) return level;

        let str = '';
        switch (Number(level)) {
            case 0:
                str = 'error';
                break;
            case 1:
                str = 'warn';
                break;
            case 2:
                str = 'info';
                break;
            case 3:
                str = 'debug';
                break;
        }

        return str;
    }
70516
function Logger () {
  const levels = [
    'fatal', // 1
    'error', // 2
    'warn', // 3
    'info', // 4
    'debug' // 5
  ];
  let verbosity = 3;

  levels.forEach((level, idx) => {
    this[level] = (...params) => {
      if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line
    };
  });

  this.setLevel = (_) => {
    verbosity = _;
  };

  return this;
}
280019
private Level mapLogLevel(final LogLevel logLevel) {
		if (LogLevel.DEBUG.equals(logLevel)) {
			return Level.DEBUG;
		} else if (LogLevel.TRACE.equals(logLevel)) {
			return Level.TRACE;
		} else if (LogLevel.INFO.equals(logLevel)) {
			return Level.INFO;
		} else if (LogLevel.WARN.equals(logLevel)) {
			return Level.WARN;
		} else if (LogLevel.ERROR.equals(logLevel)) {
			return Level.ERROR;
		}
		return null;
	}
658684
def get_logger(name=None, format_string=None):
    
    logging.captureWarnings(True)
    log = logging.getLogger(name)

    # Bind custom method to instance.
    # Source: https://stackoverflow.com/a/2982
    log.set_debug_level = _set_debug_level.__get__(log)
    log.set_debug_level(0)

    if not format_string:
        format_string = '[%(module)s]\t%(levelname)s\t%(message)s'

    # Setting up log formats
    log.handlers = []
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(
        logging.Formatter(format_string),
    )
    log.addHandler(handler)

    return log