Projekt

Obecné

Profil

Stáhnout (8.41 KB) Statistiky
| Větev: | Revize:
1
/*
2
* loglevel - https://github.com/pimterry/loglevel
3
*
4
* Copyright (c) 2013 Tim Perry
5
* Licensed under the MIT license.
6
*/
7
(function (root, definition) {
8
    "use strict";
9
    if (typeof define === 'function' && define.amd) {
10
        define(definition);
11
    } else if (typeof module === 'object' && module.exports) {
12
        module.exports = definition();
13
    } else {
14
        root.log = definition();
15
    }
16
}(this, function () {
17
    "use strict";
18

    
19
    // Slightly dubious tricks to cut down minimized file size
20
    var noop = function() {};
21
    var undefinedType = "undefined";
22
    var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
23
        /Trident\/|MSIE /.test(window.navigator.userAgent)
24
    );
25

    
26
    var logMethods = [
27
        "trace",
28
        "debug",
29
        "info",
30
        "warn",
31
        "error"
32
    ];
33

    
34
    // Cross-browser bind equivalent that works at least back to IE6
35
    function bindMethod(obj, methodName) {
36
        var method = obj[methodName];
37
        if (typeof method.bind === 'function') {
38
            return method.bind(obj);
39
        } else {
40
            try {
41
                return Function.prototype.bind.call(method, obj);
42
            } catch (e) {
43
                // Missing bind shim or IE8 + Modernizr, fallback to wrapping
44
                return function() {
45
                    return Function.prototype.apply.apply(method, [obj, arguments]);
46
                };
47
            }
48
        }
49
    }
50

    
51
    // Trace() doesn't print the message in IE, so for that case we need to wrap it
52
    function traceForIE() {
53
        if (console.log) {
54
            if (console.log.apply) {
55
                console.log.apply(console, arguments);
56
            } else {
57
                // In old IE, native console methods themselves don't have apply().
58
                Function.prototype.apply.apply(console.log, [console, arguments]);
59
            }
60
        }
61
        if (console.trace) console.trace();
62
    }
63

    
64
    // Build the best logging method possible for this env
65
    // Wherever possible we want to bind, not wrap, to preserve stack traces
66
    function realMethod(methodName) {
67
        if (methodName === 'debug') {
68
            methodName = 'log';
69
        }
70

    
71
        if (typeof console === undefinedType) {
72
            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
73
        } else if (methodName === 'trace' && isIE) {
74
            return traceForIE;
75
        } else if (console[methodName] !== undefined) {
76
            return bindMethod(console, methodName);
77
        } else if (console.log !== undefined) {
78
            return bindMethod(console, 'log');
79
        } else {
80
            return noop;
81
        }
82
    }
83

    
84
    // These private functions always need `this` to be set properly
85

    
86
    function replaceLoggingMethods(level, loggerName) {
87
        /*jshint validthis:true */
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
        // Define log.log as an alias for log.debug
96
        this.log = this.debug;
97
    }
98

    
99
    // In old IE versions, the console isn't present until you first open it.
100
    // We build realMethod() replacements here that regenerate logging methods
101
    function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
102
        return function () {
103
            if (typeof console !== undefinedType) {
104
                replaceLoggingMethods.call(this, level, loggerName);
105
                this[methodName].apply(this, arguments);
106
            }
107
        };
108
    }
109

    
110
    // By default, we use closely bound real methods wherever possible, and
111
    // otherwise we wait for a console to appear, and then try again.
112
    function defaultMethodFactory(methodName, level, loggerName) {
113
        /*jshint validthis:true */
114
        return realMethod(methodName) ||
115
               enableLoggingWhenConsoleArrives.apply(this, arguments);
116
    }
117

    
118
    function Logger(name, defaultLevel, factory) {
119
      var self = this;
120
      var currentLevel;
121
      var storageKey = "loglevel";
122
      if (name) {
123
        storageKey += ":" + name;
124
      }
125

    
126
      function persistLevelIfPossible(levelNum) {
127
          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
128

    
129
          if (typeof window === undefinedType) return;
130

    
131
          // Use localStorage if available
132
          try {
133
              window.localStorage[storageKey] = levelName;
134
              return;
135
          } catch (ignore) {}
136

    
137
          // Use session cookie as fallback
138
          try {
139
              window.document.cookie =
140
                encodeURIComponent(storageKey) + "=" + levelName + ";";
141
          } catch (ignore) {}
142
      }
143

    
144
      function getPersistedLevel() {
145
          var storedLevel;
146

    
147
          if (typeof window === undefinedType) return;
148

    
149
          try {
150
              storedLevel = window.localStorage[storageKey];
151
          } catch (ignore) {}
152

    
153
          // Fallback to cookies if local storage gives us nothing
154
          if (typeof storedLevel === undefinedType) {
155
              try {
156
                  var cookie = window.document.cookie;
157
                  var location = cookie.indexOf(
158
                      encodeURIComponent(storageKey) + "=");
159
                  if (location !== -1) {
160
                      storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
161
                  }
162
              } catch (ignore) {}
163
          }
164

    
165
          // If the stored level is not valid, treat it as if nothing was stored.
166
          if (self.levels[storedLevel] === undefined) {
167
              storedLevel = undefined;
168
          }
169

    
170
          return storedLevel;
171
      }
172

    
173
      /*
174
       *
175
       * Public logger API - see https://github.com/pimterry/loglevel for details
176
       *
177
       */
178

    
179
      self.name = name;
180

    
181
      self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
182
          "ERROR": 4, "SILENT": 5};
183

    
184
      self.methodFactory = factory || defaultMethodFactory;
185

    
186
      self.getLevel = function () {
187
          return currentLevel;
188
      };
189

    
190
      self.setLevel = function (level, persist) {
191
          if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
192
              level = self.levels[level.toUpperCase()];
193
          }
194
          if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
195
              currentLevel = level;
196
              if (persist !== false) {  // defaults to true
197
                  persistLevelIfPossible(level);
198
              }
199
              replaceLoggingMethods.call(self, level, name);
200
              if (typeof console === undefinedType && level < self.levels.SILENT) {
201
                  return "No console available for logging";
202
              }
203
          } else {
204
              throw "log.setLevel() called with invalid level: " + level;
205
          }
206
      };
207

    
208
      self.setDefaultLevel = function (level) {
209
          if (!getPersistedLevel()) {
210
              self.setLevel(level, false);
211
          }
212
      };
213

    
214
      self.enableAll = function(persist) {
215
          self.setLevel(self.levels.TRACE, persist);
216
      };
217

    
218
      self.disableAll = function(persist) {
219
          self.setLevel(self.levels.SILENT, persist);
220
      };
221

    
222
      // Initialize with the right level
223
      var initialLevel = getPersistedLevel();
224
      if (initialLevel == null) {
225
          initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
226
      }
227
      self.setLevel(initialLevel, false);
228
    }
229

    
230
    /*
231
     *
232
     * Top-level API
233
     *
234
     */
235

    
236
    var defaultLogger = new Logger();
237

    
238
    var _loggersByName = {};
239
    defaultLogger.getLogger = function getLogger(name) {
240
        if (typeof name !== "string" || name === "") {
241
          throw new TypeError("You must supply a name when creating a logger.");
242
        }
243

    
244
        var logger = _loggersByName[name];
245
        if (!logger) {
246
          logger = _loggersByName[name] = new Logger(
247
            name, defaultLogger.getLevel(), defaultLogger.methodFactory);
248
        }
249
        return logger;
250
    };
251

    
252
    // Grab the current global log variable in case of overwrite
253
    var _log = (typeof window !== undefinedType) ? window.log : undefined;
254
    defaultLogger.noConflict = function() {
255
        if (typeof window !== undefinedType &&
256
               window.log === defaultLogger) {
257
            window.log = _log;
258
        }
259

    
260
        return defaultLogger;
261
    };
262

    
263
    defaultLogger.getLoggers = function getLoggers() {
264
        return _loggersByName;
265
    };
266

    
267
    return defaultLogger;
268
}));
(2-2/2)