JSFiddle - React, Tailwind, and code Playground
by robatron
HTML
<h1>Log wrapping demo</h1>
<p>
<b>Open the browser's console (F12) to see demo output.</b>
</p>
<p>
This is a demonstration of wrapping `console.log` (et al.) to include a
<code>DEBUG</code> enable flag, and log message prefixing, written for
<a href="https://gist.github.com/robatron/5681424">
JavaScript Log Wrapping
</a>.
</p>
JavaScript
var DEBUG = true;
var LOG_PREFIX = "[MyClass]";
var log = function(){
/** Log a message to the console, prepended with `LOG_PREFIX`, granted
`DEBUG` is set.
*/
if(DEBUG){
// Convert args to a normal array
var args = Array.prototype.slice.call(arguments);
// Prepend log prefix log string
args.unshift(LOG_PREFIX + " ");
// Pass along arguments to console.log
console.log.apply(console, args);
}
}
var warn = function(){
/** Same idea as `log` but with `console.warn`...
*/
if(DEBUG){
var args = Array.prototype.slice.call(arguments);
args.unshift(LOG_PREFIX + " ");
console.warn.apply(console, args);
}
}
var err = function(){
if(DEBUG){
var args = Array.prototype.slice.call(arguments);
args.unshift(LOG_PREFIX + " ");
console.error.apply(console, args);
}
}
// Demo
// ----
log("Hello!");
log("");
log("This is a demonstration of log wrapping. Benefits include flaggable " +
"log enabling, log prefixing, or anything else you might want to do " +
"when logging from your application.");
log("");
log("<--- Note the log prefix for identifying message origin");
log("");
log("Logging arbitrary numbers of arguments, with full console object " +
"browsing as supported by the original `console.log`:")
var arr = [1, 2, 3];
var obj = {
a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10, k:11, l:12, m:13, n:14,
o:15, p:16, q:17, r:18, s:19, t:20, u:21, v:22, w:23, x:24, y:25, z:26
};
var func = function(msg){alert(msg);};
log(" arr =", arr, ", obj =", obj, ", func =", func);
log("");
warn("Warning! Exact same idea for warn and error logging.")
err("Error! Same idea for error logging too.");
log("");
log("Neat, eh?\n")