MDL-56010 libraries: Upgrade loglevel.js to 1.4.1 - library import
[moodle.git] / lib / amd / src / loglevel.js
CommitLineData
0b8cdaf6
JD
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
23 // Build the best logging method possible for this env
24 // Wherever possible we want to bind, not wrap, to preserve stack traces
25 function realMethod(methodName) {
26 if (typeof console === undefinedType) {
27 return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
28 } else if (console[methodName] !== undefined) {
29 return bindMethod(console, methodName);
30 } else if (console.log !== undefined) {
31 return bindMethod(console, 'log');
32 } else {
33 return noop;
34 }
35 }
36
37 // Cross-browser bind equivalent that works at least back to IE6
38 function bindMethod(obj, methodName) {
39 var method = obj[methodName];
40 if (typeof method.bind === 'function') {
41 return method.bind(obj);
42 } else {
43 try {
44 return Function.prototype.bind.call(method, obj);
45 } catch (e) {
46 // Missing bind shim or IE8 + Modernizr, fallback to wrapping
47 return function() {
48 return Function.prototype.apply.apply(method, [obj, arguments]);
49 };
50 }
51 }
52 }
53
54 // These private functions always need `this` to be set properly
55
56 // In old IE versions, the console isn't present until you first open it.
57 // We build realMethod() replacements here that regenerate logging methods
58 function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
59 return function () {
60 if (typeof console !== undefinedType) {
61 replaceLoggingMethods.call(this, level, loggerName);
62 this[methodName].apply(this, arguments);
63 }
64 };
65 }
66
67 function replaceLoggingMethods(level, loggerName) {
68 /*jshint validthis:true */
69 for (var i = 0; i < logMethods.length; i++) {
70 var methodName = logMethods[i];
71 this[methodName] = (i < level) ?
72 noop :
73 this.methodFactory(methodName, level, loggerName);
74 }
75 }
76
77 // By default, we use closely bound real methods wherever possible, and
78 // otherwise we wait for a console to appear, and then try again.
79 function defaultMethodFactory(methodName, level, loggerName) {
80 /*jshint validthis:true */
81 return realMethod(methodName) ||
82 enableLoggingWhenConsoleArrives.apply(this, arguments);
83 }
84
85 var logMethods = [
86 "trace",
87 "debug",
88 "info",
89 "warn",
90 "error"
91 ];
92
93 function Logger(name, defaultLevel, factory) {
94 var self = this;
95 var currentLevel;
96 var storageKey = "loglevel";
97 if (name) {
98 storageKey += ":" + name;
99 }
100
101 function persistLevelIfPossible(levelNum) {
102 var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
103
104 // Use localStorage if available
105 try {
106 window.localStorage[storageKey] = levelName;
107 return;
108 } catch (ignore) {}
109
110 // Use session cookie as fallback
111 try {
112 window.document.cookie =
113 encodeURIComponent(storageKey) + "=" + levelName + ";";
114 } catch (ignore) {}
115 }
116
117 function getPersistedLevel() {
118 var storedLevel;
119
120 try {
121 storedLevel = window.localStorage[storageKey];
122 } catch (ignore) {}
123
124 // Fallback to cookies if local storage gives us nothing
125 if (typeof storedLevel === undefinedType) {
126 try {
127 var cookie = window.document.cookie;
128 var location = cookie.indexOf(
129 encodeURIComponent(storageKey) + "=");
130 if (location) {
131 storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
132 }
133 } catch (ignore) {}
134 }
135
136 // If the stored level is not valid, treat it as if nothing was stored.
137 if (self.levels[storedLevel] === undefined) {
138 storedLevel = undefined;
139 }
140
141 return storedLevel;
142 }
143
144 /*
145 *
146 * Public logger API - see https://github.com/pimterry/loglevel for details
147 *
148 */
149
150 self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
151 "ERROR": 4, "SILENT": 5};
152
153 self.methodFactory = factory || defaultMethodFactory;
154
155 self.getLevel = function () {
156 return currentLevel;
157 };
158
159 self.setLevel = function (level, persist) {
160 if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
161 level = self.levels[level.toUpperCase()];
162 }
163 if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
164 currentLevel = level;
165 if (persist !== false) { // defaults to true
166 persistLevelIfPossible(level);
167 }
168 replaceLoggingMethods.call(self, level, name);
169 if (typeof console === undefinedType && level < self.levels.SILENT) {
170 return "No console available for logging";
171 }
172 } else {
173 throw "log.setLevel() called with invalid level: " + level;
174 }
175 };
176
177 self.setDefaultLevel = function (level) {
178 if (!getPersistedLevel()) {
179 self.setLevel(level, false);
180 }
181 };
182
183 self.enableAll = function(persist) {
184 self.setLevel(self.levels.TRACE, persist);
185 };
186
187 self.disableAll = function(persist) {
188 self.setLevel(self.levels.SILENT, persist);
189 };
190
191 // Initialize with the right level
192 var initialLevel = getPersistedLevel();
193 if (initialLevel == null) {
194 initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
195 }
196 self.setLevel(initialLevel, false);
197 }
198
199 /*
200 *
201 * Top-level API
202 *
203 */
204
205 var defaultLogger = new Logger();
206
207 var _loggersByName = {};
208 defaultLogger.getLogger = function getLogger(name) {
209 if (typeof name !== "string" || name === "") {
210 throw new TypeError("You must supply a name when creating a logger.");
211 }
212
213 var logger = _loggersByName[name];
214 if (!logger) {
215 logger = _loggersByName[name] = new Logger(
216 name, defaultLogger.getLevel(), defaultLogger.methodFactory);
217 }
218 return logger;
219 };
220
221 // Grab the current global log variable in case of overwrite
222 var _log = (typeof window !== undefinedType) ? window.log : undefined;
223 defaultLogger.noConflict = function() {
224 if (typeof window !== undefinedType &&
225 window.log === defaultLogger) {
226 window.log = _log;
227 }
228
229 return defaultLogger;
230 };
231
232 return defaultLogger;
233}));