[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/amd/src/ -> loglevel.js (source)

   1  // The MIT License

   2  //

   3  // Copyright (c) 2014 Tom Perry

   4  //

   5  // Permission is hereby granted, free of charge, to any person obtaining

   6  // a copy of this software and associated documentation files (the

   7  // "Software"), to deal in the Software without restriction, including

   8  // without limitation the rights to use, copy, modify, merge, publish,

   9  // distribute, sublicense, and/or sell copies of the Software, and to

  10  // permit persons to whom the Software is furnished to do so, subject to

  11  // the following conditions:

  12  //

  13  // The above copyright notice and this permission notice shall be

  14  // included in all copies or substantial portions of the Software.

  15  //

  16  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

  17  // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

  18  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

  19  // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY

  20  // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,

  21  // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE

  22  // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  23  //

  24  
  25  // Description of import into Moodle:

  26  // Download from https://github.com/pimterry/loglevel/releases

  27  // Copy loglevel.js into lib/amd/src/ in Moodle folder.

  28  // Add the license as a comment to the file and these instructions.

  29  // Add the jshint ignore:start and ignore:end comments.

  30  // Delete the jshint validthis:true comments.

  31  
  32  /* jshint ignore:start */

  33  /*! loglevel - v1.4.0 - https://github.com/pimterry/loglevel - (c) 2015 Tim Perry - licensed MIT */

  34  (function (root, definition) {
  35      "use strict";
  36      if (typeof module === 'object' && module.exports && typeof require === 'function') {
  37          module.exports = definition();
  38      } else if (typeof define === 'function' && typeof define.amd === 'object') {
  39          define(definition);
  40      } else {
  41          root.log = definition();
  42      }
  43  }(this, function () {
  44      "use strict";
  45      var noop = function() {};
  46      var undefinedType = "undefined";
  47  
  48      function realMethod(methodName) {
  49          if (typeof console === undefinedType) {
  50              return false; // We can't build a real method without a console to log to

  51          } else if (console[methodName] !== undefined) {
  52              return bindMethod(console, methodName);
  53          } else if (console.log !== undefined) {
  54              return bindMethod(console, 'log');
  55          } else {
  56              return noop;
  57          }
  58      }
  59  
  60      function bindMethod(obj, methodName) {
  61          var method = obj[methodName];
  62          if (typeof method.bind === 'function') {
  63              return method.bind(obj);
  64          } else {
  65              try {
  66                  return Function.prototype.bind.call(method, obj);
  67              } catch (e) {
  68                  // Missing bind shim or IE8 + Modernizr, fallback to wrapping

  69                  return function() {
  70                      return Function.prototype.apply.apply(method, [obj, arguments]);
  71                  };
  72              }
  73          }
  74      }
  75  
  76      // these private functions always need `this` to be set properly

  77  
  78      function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
  79          return function () {
  80              if (typeof console !== undefinedType) {
  81                  replaceLoggingMethods.call(this, level, loggerName);
  82                  this[methodName].apply(this, arguments);
  83              }
  84          };
  85      }
  86  
  87      function replaceLoggingMethods(level, loggerName) {
  88          for (var i = 0; i < logMethods.length; i++) {
  89              var methodName = logMethods[i];
  90              this[methodName] = (i < level) ?
  91                  noop :
  92                  this.methodFactory(methodName, level, loggerName);
  93          }
  94      }
  95  
  96      function defaultMethodFactory(methodName, level, loggerName) {
  97          return realMethod(methodName) ||
  98                 enableLoggingWhenConsoleArrives.apply(this, arguments);
  99      }
 100  
 101      var logMethods = [
 102          "trace",
 103          "debug",
 104          "info",
 105          "warn",
 106          "error"
 107      ];
 108  
 109      function Logger(name, defaultLevel, factory) {
 110        var self = this;
 111        var currentLevel;
 112        var storageKey = "loglevel";
 113        if (name) {
 114          storageKey += ":" + name;
 115        }
 116  
 117        function persistLevelIfPossible(levelNum) {
 118            var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
 119  
 120            // Use localStorage if available

 121            try {
 122                window.localStorage[storageKey] = levelName;
 123                return;
 124            } catch (ignore) {}
 125  
 126            // Use session cookie as fallback

 127            try {
 128                window.document.cookie =
 129                  encodeURIComponent(storageKey) + "=" + levelName + ";";
 130            } catch (ignore) {}
 131        }
 132  
 133        function getPersistedLevel() {
 134            var storedLevel;
 135  
 136            try {
 137                storedLevel = window.localStorage[storageKey];
 138            } catch (ignore) {}
 139  
 140            if (typeof storedLevel === undefinedType) {
 141                try {
 142                    var cookie = window.document.cookie;
 143                    var location = cookie.indexOf(
 144                        encodeURIComponent(storageKey) + "=");
 145                    if (location) {
 146                        storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
 147                    }
 148                } catch (ignore) {}
 149            }
 150  
 151            // If the stored level is not valid, treat it as if nothing was stored.

 152            if (self.levels[storedLevel] === undefined) {
 153                storedLevel = undefined;
 154            }
 155  
 156            return storedLevel;
 157        }
 158  
 159        /*

 160         *

 161         * Public API

 162         *

 163         */
 164  
 165        self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
 166            "ERROR": 4, "SILENT": 5};
 167  
 168        self.methodFactory = factory || defaultMethodFactory;
 169  
 170        self.getLevel = function () {
 171            return currentLevel;
 172        };
 173  
 174        self.setLevel = function (level, persist) {
 175            if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
 176                level = self.levels[level.toUpperCase()];
 177            }
 178            if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
 179                currentLevel = level;
 180                if (persist !== false) {  // defaults to true
 181                    persistLevelIfPossible(level);
 182                }
 183                replaceLoggingMethods.call(self, level, name);
 184                if (typeof console === undefinedType && level < self.levels.SILENT) {
 185                    return "No console available for logging";
 186                }
 187            } else {
 188                throw "log.setLevel() called with invalid level: " + level;
 189            }
 190        };
 191  
 192        self.setDefaultLevel = function (level) {
 193            if (!getPersistedLevel()) {
 194                self.setLevel(level, false);
 195            }
 196        };
 197  
 198        self.enableAll = function(persist) {
 199            self.setLevel(self.levels.TRACE, persist);
 200        };
 201  
 202        self.disableAll = function(persist) {
 203            self.setLevel(self.levels.SILENT, persist);
 204        };
 205  
 206        // Initialize with the right level

 207        var initialLevel = getPersistedLevel();
 208        if (initialLevel == null) {
 209            initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
 210        }
 211        self.setLevel(initialLevel, false);
 212      }
 213  
 214      /*

 215       *

 216       * Package-level API

 217       *

 218       */
 219  
 220      var defaultLogger = new Logger();
 221  
 222      var _loggersByName = {};
 223      defaultLogger.getLogger = function getLogger(name) {
 224          if (typeof name !== "string" || name === "") {
 225            throw new TypeError("You must supply a name when creating a logger.");
 226          }
 227  
 228          var logger = _loggersByName[name];
 229          if (!logger) {
 230            logger = _loggersByName[name] = new Logger(
 231              name, defaultLogger.getLevel(), defaultLogger.methodFactory);
 232          }
 233          return logger;
 234      };
 235  
 236      // Grab the current global log variable in case of overwrite

 237      var _log = (typeof window !== undefinedType) ? window.log : undefined;
 238      defaultLogger.noConflict = function() {
 239          if (typeof window !== undefinedType &&
 240                 window.log === defaultLogger) {
 241              window.log = _log;
 242          }
 243  
 244          return defaultLogger;
 245      };
 246  
 247      return defaultLogger;
 248  }));
 249  /* jshint ignore:end */



Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1