Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// Copyright (c) 2013 Tim Perry
2
//
3
// Permission is hereby granted, free of charge, to any person
4
// obtaining a copy of this software and associated documentation
5
// files (the "Software"), to deal in the Software without
6
// restriction, including without limitation the rights to use,
7
// copy, modify, merge, publish, distribute, sublicense, and/or sell
8
// copies of the Software, and to permit persons to whom the
9
// Software is furnished to do so, subject to the following
10
// conditions:
11
//
12
// The above copyright notice and this permission notice shall be
13
// included in all copies or substantial portions of the Software.
14
//
15
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
// OTHER DEALINGS IN THE SOFTWARE.
23
 
24
// Description of import into Moodle:
25
// Download from https://github.com/pimterry/loglevel/tree/master/dist
26
// Copy loglevel.js into lib/amd/src/ in Moodle folder.
27
// Add the license as a comment to the file and these instructions.
28
 
29
/*! loglevel - v1.8.1 - https://github.com/pimterry/loglevel - (c) 2022 Tim Perry - licensed MIT */
30
(function (root, definition) {
31
    "use strict";
32
    if (typeof define === 'function' && define.amd) {
33
        define(definition);
34
    } else if (typeof module === 'object' && module.exports) {
35
        module.exports = definition();
36
    } else {
37
        root.log = definition();
38
    }
39
}(this, function () {
40
    "use strict";
41
 
42
    // Slightly dubious tricks to cut down minimized file size
43
    var noop = function() {};
44
    var undefinedType = "undefined";
45
    var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
46
        /Trident\/|MSIE /.test(window.navigator.userAgent)
47
    );
48
 
49
    var logMethods = [
50
        "trace",
51
        "debug",
52
        "info",
53
        "warn",
54
        "error"
55
    ];
56
 
57
    // Cross-browser bind equivalent that works at least back to IE6
58
    function bindMethod(obj, methodName) {
59
        var method = obj[methodName];
60
        if (typeof method.bind === 'function') {
61
            return method.bind(obj);
62
        } else {
63
            try {
64
                return Function.prototype.bind.call(method, obj);
65
            } catch (e) {
66
                // Missing bind shim or IE8 + Modernizr, fallback to wrapping
67
                return function() {
68
                    return Function.prototype.apply.apply(method, [obj, arguments]);
69
                };
70
            }
71
        }
72
    }
73
 
74
    // Trace() doesn't print the message in IE, so for that case we need to wrap it
75
    function traceForIE() {
76
        if (console.log) {
77
            if (console.log.apply) {
78
                console.log.apply(console, arguments);
79
            } else {
80
                // In old IE, native console methods themselves don't have apply().
81
                Function.prototype.apply.apply(console.log, [console, arguments]);
82
            }
83
        }
84
        if (console.trace) console.trace();
85
    }
86
 
87
    // Build the best logging method possible for this env
88
    // Wherever possible we want to bind, not wrap, to preserve stack traces
89
    function realMethod(methodName) {
90
        if (methodName === 'debug') {
91
            methodName = 'log';
92
        }
93
 
94
        if (typeof console === undefinedType) {
95
            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
96
        } else if (methodName === 'trace' && isIE) {
97
            return traceForIE;
98
        } else if (console[methodName] !== undefined) {
99
            return bindMethod(console, methodName);
100
        } else if (console.log !== undefined) {
101
            return bindMethod(console, 'log');
102
        } else {
103
            return noop;
104
        }
105
    }
106
 
107
    // These private functions always need `this` to be set properly
108
 
109
    function replaceLoggingMethods(level, loggerName) {
110
        /*jshint validthis:true */
111
        for (var i = 0; i < logMethods.length; i++) {
112
            var methodName = logMethods[i];
113
            this[methodName] = (i < level) ?
114
                noop :
115
                this.methodFactory(methodName, level, loggerName);
116
        }
117
 
118
        // Define log.log as an alias for log.debug
119
        this.log = this.debug;
120
    }
121
 
122
    // In old IE versions, the console isn't present until you first open it.
123
    // We build realMethod() replacements here that regenerate logging methods
124
    function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
125
        return function () {
126
            if (typeof console !== undefinedType) {
127
                replaceLoggingMethods.call(this, level, loggerName);
128
                this[methodName].apply(this, arguments);
129
            }
130
        };
131
    }
132
 
133
    // By default, we use closely bound real methods wherever possible, and
134
    // otherwise we wait for a console to appear, and then try again.
135
    function defaultMethodFactory(methodName, level, loggerName) {
136
        /*jshint validthis:true */
137
        return realMethod(methodName) ||
138
               enableLoggingWhenConsoleArrives.apply(this, arguments);
139
    }
140
 
141
    function Logger(name, defaultLevel, factory) {
142
      var self = this;
143
      var currentLevel;
144
      defaultLevel = defaultLevel == null ? "WARN" : defaultLevel;
145
 
146
      var storageKey = "loglevel";
147
      if (typeof name === "string") {
148
        storageKey += ":" + name;
149
      } else if (typeof name === "symbol") {
150
        storageKey = undefined;
151
      }
152
 
153
      function persistLevelIfPossible(levelNum) {
154
          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
155
 
156
          if (typeof window === undefinedType || !storageKey) return;
157
 
158
          // Use localStorage if available
159
          try {
160
              window.localStorage[storageKey] = levelName;
161
              return;
162
          } catch (ignore) {}
163
 
164
          // Use session cookie as fallback
165
          try {
166
              window.document.cookie =
167
                encodeURIComponent(storageKey) + "=" + levelName + ";";
168
          } catch (ignore) {}
169
      }
170
 
171
      function getPersistedLevel() {
172
          var storedLevel;
173
 
174
          if (typeof window === undefinedType || !storageKey) return;
175
 
176
          try {
177
              storedLevel = window.localStorage[storageKey];
178
          } catch (ignore) {}
179
 
180
          // Fallback to cookies if local storage gives us nothing
181
          if (typeof storedLevel === undefinedType) {
182
              try {
183
                  var cookie = window.document.cookie;
184
                  var location = cookie.indexOf(
185
                      encodeURIComponent(storageKey) + "=");
186
                  if (location !== -1) {
187
                      storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
188
                  }
189
              } catch (ignore) {}
190
          }
191
 
192
          // If the stored level is not valid, treat it as if nothing was stored.
193
          if (self.levels[storedLevel] === undefined) {
194
              storedLevel = undefined;
195
          }
196
 
197
          return storedLevel;
198
      }
199
 
200
      function clearPersistedLevel() {
201
          if (typeof window === undefinedType || !storageKey) return;
202
 
203
          // Use localStorage if available
204
          try {
205
              window.localStorage.removeItem(storageKey);
206
              return;
207
          } catch (ignore) {}
208
 
209
          // Use session cookie as fallback
210
          try {
211
              window.document.cookie =
212
                encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
213
          } catch (ignore) {}
214
      }
215
 
216
      /*
217
       *
218
       * Public logger API - see https://github.com/pimterry/loglevel for details
219
       *
220
       */
221
 
222
      self.name = name;
223
 
224
      self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
225
          "ERROR": 4, "SILENT": 5};
226
 
227
      self.methodFactory = factory || defaultMethodFactory;
228
 
229
      self.getLevel = function () {
230
          return currentLevel;
231
      };
232
 
233
      self.setLevel = function (level, persist) {
234
          if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
235
              level = self.levels[level.toUpperCase()];
236
          }
237
          if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
238
              currentLevel = level;
239
              if (persist !== false) {  // defaults to true
240
                  persistLevelIfPossible(level);
241
              }
242
              replaceLoggingMethods.call(self, level, name);
243
              if (typeof console === undefinedType && level < self.levels.SILENT) {
244
                  return "No console available for logging";
245
              }
246
          } else {
247
              throw "log.setLevel() called with invalid level: " + level;
248
          }
249
      };
250
 
251
      self.setDefaultLevel = function (level) {
252
          defaultLevel = level;
253
          if (!getPersistedLevel()) {
254
              self.setLevel(level, false);
255
          }
256
      };
257
 
258
      self.resetLevel = function () {
259
          self.setLevel(defaultLevel, false);
260
          clearPersistedLevel();
261
      };
262
 
263
      self.enableAll = function(persist) {
264
          self.setLevel(self.levels.TRACE, persist);
265
      };
266
 
267
      self.disableAll = function(persist) {
268
          self.setLevel(self.levels.SILENT, persist);
269
      };
270
 
271
      // Initialize with the right level
272
      var initialLevel = getPersistedLevel();
273
      if (initialLevel == null) {
274
          initialLevel = defaultLevel;
275
      }
276
      self.setLevel(initialLevel, false);
277
    }
278
 
279
    /*
280
     *
281
     * Top-level API
282
     *
283
     */
284
 
285
    var defaultLogger = new Logger();
286
 
287
    var _loggersByName = {};
288
    defaultLogger.getLogger = function getLogger(name) {
289
        if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
290
          throw new TypeError("You must supply a name when creating a logger.");
291
        }
292
 
293
        var logger = _loggersByName[name];
294
        if (!logger) {
295
          logger = _loggersByName[name] = new Logger(
296
            name, defaultLogger.getLevel(), defaultLogger.methodFactory);
297
        }
298
        return logger;
299
    };
300
 
301
    // Grab the current global log variable in case of overwrite
302
    var _log = (typeof window !== undefinedType) ? window.log : undefined;
303
    defaultLogger.noConflict = function() {
304
        if (typeof window !== undefinedType &&
305
               window.log === defaultLogger) {
306
            window.log = _log;
307
        }
308
 
309
        return defaultLogger;
310
    };
311
 
312
    defaultLogger.getLoggers = function getLoggers() {
313
        return _loggersByName;
314
    };
315
 
316
    // ES6 default export, for compatibility
317
    defaultLogger['default'] = defaultLogger;
318
 
319
    return defaultLogger;
320
}));