# Code coverage report for logdriver/index.js

## Statements: 97.22% (35 / 36) Branches: 93.75% (15 / 16) Functions: 100% (8 / 8) Lines: 97.22% (35 / 36) Ignored: none

All files » logdriver/ » index.js

    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
    611

    1
    5
    5
    5
    1

    5
    5
    1

    4
    4

    5
    23
    16
    4
    4
    4

    7

    1
    23
    5

    18

    1
    3

    3
    3
    3

    3

    1

    1
    5
    5
    5

    1

    1
     var util = require('util');

    LogDriver = function(options){
      options = options || {};
      var logger = this;
      if (options.format){
        this.format = options.format;
      }
      this.levels = options.levels || ['error', 'warn', 'info', 'debug', 'trace'];
      if (options.level === false){
        this.level = false;  // don't log anything
      } else {
        this.level = options.level || this.levels[this.levels.length - 1];
        Iif (this.levels.indexOf(this.level) === -1){
          throw new Error("Log level '" +
                          this.level +
                          "' does not exist in level list '" + JSON.stringify() + "'");
        }
      }
      this.levels.forEach(function(level){
        if (logLevelShouldOutput(level, logger.level, logger.levels)){
          logger[level] = function(){
            var args = Array.prototype.slice.call(arguments);
            args.unshift(level);  // log level is added as the first parameter
            console.log(logger.format.apply(logger, args));
          };
        } else {
          logger[level] = function(){/* no-op, because this log level is ignored */};
        }
      });
    };

    var logLevelShouldOutput = function(logLevel, configuredLevel, levels){
      if (configuredLevel === false){
        return false;
      }
      return (levels.indexOf(logLevel) <= levels.indexOf(configuredLevel));
    };

    LogDriver.prototype.format = function(){
      var args = Array.prototype.slice.call(arguments, [1]); // change arguments to an array, but
                                                             // drop the first item (log level)
      var out = "[" + arguments[0] + "] " + JSON.stringify(new Date()) + " ";
      args.forEach(function(arg){
        out += " " + util.inspect(arg);
      });
      return out;
    };

    var defaultLogger = null;

    factory = function(options){
      defaultLogger = new LogDriver(options);
      factory.logger = defaultLogger;
      return defaultLogger;
    };

    factory();

    module.exports = factory;