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