Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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:
1441 ariadna 25
// Download from https://github.com/pimterry/loglevel/tree/main/dist
26
// Copy loglevel.js into lib/amd/src/ in Moodle folder, and use grunt to build the code
1 efrain 27
// Add the license as a comment to the file and these instructions.
28
 
1441 ariadna 29
/*! loglevel - v1.9.2 - https://github.com/pimterry/loglevel - (c) 2024 Tim Perry - licensed MIT */
1 efrain 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
 
1441 ariadna 57
    var _loggersByName = {};
58
    var defaultLogger = null;
59
 
1 efrain 60
    // Cross-browser bind equivalent that works at least back to IE6
61
    function bindMethod(obj, methodName) {
62
        var method = obj[methodName];
63
        if (typeof method.bind === 'function') {
64
            return method.bind(obj);
65
        } else {
66
            try {
67
                return Function.prototype.bind.call(method, obj);
68
            } catch (e) {
69
                // Missing bind shim or IE8 + Modernizr, fallback to wrapping
70
                return function() {
71
                    return Function.prototype.apply.apply(method, [obj, arguments]);
72
                };
73
            }
74
        }
75
    }
76
 
77
    // Trace() doesn't print the message in IE, so for that case we need to wrap it
78
    function traceForIE() {
79
        if (console.log) {
80
            if (console.log.apply) {
81
                console.log.apply(console, arguments);
82
            } else {
83
                // In old IE, native console methods themselves don't have apply().
84
                Function.prototype.apply.apply(console.log, [console, arguments]);
85
            }
86
        }
87
        if (console.trace) console.trace();
88
    }
89
 
90
    // Build the best logging method possible for this env
91
    // Wherever possible we want to bind, not wrap, to preserve stack traces
92
    function realMethod(methodName) {
93
        if (methodName === 'debug') {
94
            methodName = 'log';
95
        }
96
 
97
        if (typeof console === undefinedType) {
98
            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
99
        } else if (methodName === 'trace' && isIE) {
100
            return traceForIE;
101
        } else if (console[methodName] !== undefined) {
102
            return bindMethod(console, methodName);
103
        } else if (console.log !== undefined) {
104
            return bindMethod(console, 'log');
105
        } else {
106
            return noop;
107
        }
108
    }
109
 
110
    // These private functions always need `this` to be set properly
111
 
1441 ariadna 112
    function replaceLoggingMethods() {
1 efrain 113
        /*jshint validthis:true */
1441 ariadna 114
        var level = this.getLevel();
115
 
116
        // Replace the actual methods.
1 efrain 117
        for (var i = 0; i < logMethods.length; i++) {
118
            var methodName = logMethods[i];
119
            this[methodName] = (i < level) ?
120
                noop :
1441 ariadna 121
                this.methodFactory(methodName, level, this.name);
1 efrain 122
        }
123
 
124
        // Define log.log as an alias for log.debug
125
        this.log = this.debug;
1441 ariadna 126
 
127
        // Return any important warnings.
128
        if (typeof console === undefinedType && level < this.levels.SILENT) {
129
            return "No console available for logging";
130
        }
1 efrain 131
    }
132
 
133
    // In old IE versions, the console isn't present until you first open it.
134
    // We build realMethod() replacements here that regenerate logging methods
1441 ariadna 135
    function enableLoggingWhenConsoleArrives(methodName) {
1 efrain 136
        return function () {
137
            if (typeof console !== undefinedType) {
1441 ariadna 138
                replaceLoggingMethods.call(this);
1 efrain 139
                this[methodName].apply(this, arguments);
140
            }
141
        };
142
    }
143
 
144
    // By default, we use closely bound real methods wherever possible, and
145
    // otherwise we wait for a console to appear, and then try again.
1441 ariadna 146
    function defaultMethodFactory(methodName, _level, _loggerName) {
1 efrain 147
        /*jshint validthis:true */
148
        return realMethod(methodName) ||
149
               enableLoggingWhenConsoleArrives.apply(this, arguments);
150
    }
151
 
1441 ariadna 152
    function Logger(name, factory) {
153
      // Private instance variables.
1 efrain 154
      var self = this;
1441 ariadna 155
      /**
156
       * The level inherited from a parent logger (or a global default). We
157
       * cache this here rather than delegating to the parent so that it stays
158
       * in sync with the actual logging methods that we have installed (the
159
       * parent could change levels but we might not have rebuilt the loggers
160
       * in this child yet).
161
       * @type {number}
162
       */
163
      var inheritedLevel;
164
      /**
165
       * The default level for this logger, if any. If set, this overrides
166
       * `inheritedLevel`.
167
       * @type {number|null}
168
       */
169
      var defaultLevel;
170
      /**
171
       * A user-specific level for this logger. If set, this overrides
172
       * `defaultLevel`.
173
       * @type {number|null}
174
       */
175
      var userLevel;
1 efrain 176
 
177
      var storageKey = "loglevel";
178
      if (typeof name === "string") {
179
        storageKey += ":" + name;
180
      } else if (typeof name === "symbol") {
181
        storageKey = undefined;
182
      }
183
 
184
      function persistLevelIfPossible(levelNum) {
185
          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
186
 
187
          if (typeof window === undefinedType || !storageKey) return;
188
 
189
          // Use localStorage if available
190
          try {
191
              window.localStorage[storageKey] = levelName;
192
              return;
193
          } catch (ignore) {}
194
 
195
          // Use session cookie as fallback
196
          try {
197
              window.document.cookie =
198
                encodeURIComponent(storageKey) + "=" + levelName + ";";
199
          } catch (ignore) {}
200
      }
201
 
202
      function getPersistedLevel() {
203
          var storedLevel;
204
 
205
          if (typeof window === undefinedType || !storageKey) return;
206
 
207
          try {
208
              storedLevel = window.localStorage[storageKey];
209
          } catch (ignore) {}
210
 
211
          // Fallback to cookies if local storage gives us nothing
212
          if (typeof storedLevel === undefinedType) {
213
              try {
214
                  var cookie = window.document.cookie;
1441 ariadna 215
                  var cookieName = encodeURIComponent(storageKey);
216
                  var location = cookie.indexOf(cookieName + "=");
1 efrain 217
                  if (location !== -1) {
1441 ariadna 218
                      storedLevel = /^([^;]+)/.exec(
219
                          cookie.slice(location + cookieName.length + 1)
220
                      )[1];
1 efrain 221
                  }
222
              } catch (ignore) {}
223
          }
224
 
225
          // If the stored level is not valid, treat it as if nothing was stored.
226
          if (self.levels[storedLevel] === undefined) {
227
              storedLevel = undefined;
228
          }
229
 
230
          return storedLevel;
231
      }
232
 
233
      function clearPersistedLevel() {
234
          if (typeof window === undefinedType || !storageKey) return;
235
 
236
          // Use localStorage if available
237
          try {
238
              window.localStorage.removeItem(storageKey);
239
          } catch (ignore) {}
240
 
241
          // Use session cookie as fallback
242
          try {
243
              window.document.cookie =
244
                encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
245
          } catch (ignore) {}
246
      }
247
 
1441 ariadna 248
      function normalizeLevel(input) {
249
          var level = input;
250
          if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
251
              level = self.levels[level.toUpperCase()];
252
          }
253
          if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
254
              return level;
255
          } else {
256
              throw new TypeError("log.setLevel() called with invalid level: " + input);
257
          }
258
      }
259
 
1 efrain 260
      /*
261
       *
262
       * Public logger API - see https://github.com/pimterry/loglevel for details
263
       *
264
       */
265
 
266
      self.name = name;
267
 
268
      self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
269
          "ERROR": 4, "SILENT": 5};
270
 
271
      self.methodFactory = factory || defaultMethodFactory;
272
 
273
      self.getLevel = function () {
1441 ariadna 274
          if (userLevel != null) {
275
            return userLevel;
276
          } else if (defaultLevel != null) {
277
            return defaultLevel;
278
          } else {
279
            return inheritedLevel;
280
          }
1 efrain 281
      };
282
 
283
      self.setLevel = function (level, persist) {
1441 ariadna 284
          userLevel = normalizeLevel(level);
285
          if (persist !== false) {  // defaults to true
286
              persistLevelIfPossible(userLevel);
1 efrain 287
          }
1441 ariadna 288
 
289
          // NOTE: in v2, this should call rebuild(), which updates children.
290
          return replaceLoggingMethods.call(self);
1 efrain 291
      };
292
 
293
      self.setDefaultLevel = function (level) {
1441 ariadna 294
          defaultLevel = normalizeLevel(level);
1 efrain 295
          if (!getPersistedLevel()) {
296
              self.setLevel(level, false);
297
          }
298
      };
299
 
300
      self.resetLevel = function () {
1441 ariadna 301
          userLevel = null;
1 efrain 302
          clearPersistedLevel();
1441 ariadna 303
          replaceLoggingMethods.call(self);
1 efrain 304
      };
305
 
306
      self.enableAll = function(persist) {
307
          self.setLevel(self.levels.TRACE, persist);
308
      };
309
 
310
      self.disableAll = function(persist) {
311
          self.setLevel(self.levels.SILENT, persist);
312
      };
313
 
1441 ariadna 314
      self.rebuild = function () {
315
          if (defaultLogger !== self) {
316
              inheritedLevel = normalizeLevel(defaultLogger.getLevel());
317
          }
318
          replaceLoggingMethods.call(self);
319
 
320
          if (defaultLogger === self) {
321
              for (var childName in _loggersByName) {
322
                _loggersByName[childName].rebuild();
323
              }
324
          }
325
      };
326
 
327
      // Initialize all the internal levels.
328
      inheritedLevel = normalizeLevel(
329
          defaultLogger ? defaultLogger.getLevel() : "WARN"
330
      );
1 efrain 331
      var initialLevel = getPersistedLevel();
1441 ariadna 332
      if (initialLevel != null) {
333
          userLevel = normalizeLevel(initialLevel);
1 efrain 334
      }
1441 ariadna 335
      replaceLoggingMethods.call(self);
1 efrain 336
    }
337
 
338
    /*
339
     *
340
     * Top-level API
341
     *
342
     */
343
 
1441 ariadna 344
    defaultLogger = new Logger();
1 efrain 345
 
346
    defaultLogger.getLogger = function getLogger(name) {
347
        if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
1441 ariadna 348
            throw new TypeError("You must supply a name when creating a logger.");
1 efrain 349
        }
350
 
351
        var logger = _loggersByName[name];
352
        if (!logger) {
1441 ariadna 353
            logger = _loggersByName[name] = new Logger(
354
                name,
355
                defaultLogger.methodFactory
356
            );
1 efrain 357
        }
358
        return logger;
359
    };
360
 
361
    // Grab the current global log variable in case of overwrite
362
    var _log = (typeof window !== undefinedType) ? window.log : undefined;
363
    defaultLogger.noConflict = function() {
364
        if (typeof window !== undefinedType &&
365
               window.log === defaultLogger) {
366
            window.log = _log;
367
        }
368
 
369
        return defaultLogger;
370
    };
371
 
372
    defaultLogger.getLoggers = function getLoggers() {
373
        return _loggersByName;
374
    };
375
 
376
    // ES6 default export, for compatibility
377
    defaultLogger['default'] = defaultLogger;
378
 
379
    return defaultLogger;
380
}));