Created
January 31, 2013 10:40
-
-
Save antila/4682026 to your computer and use it in GitHub Desktop.
Debug log helper. Never add a console.log to your code. This one also runs a stack trace to show where it got called from. Otherwise you'll just see the line in this gist as the source of the log message, and that isn't helpful since you want to see where the log call was made.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = { | |
debug: function(message, level) { | |
// Default level for logs | |
if (typeof level === 'undefined' || level === 'log') { | |
level = 'info'; | |
} | |
// If we have a console... | |
if (typeof console === 'object' && typeof console.debug === 'function') { | |
// ...and the requested log level exists | |
if (typeof console[level] === 'function') { | |
// Let's add some styling to the error log | |
var messageStyle = "display: block; font-size: 1em; line-height: 1.6em;"; | |
var fileStyle = "font-size: 0.9em; opacity: 0.6;"; | |
// Create an error so we can run a stack trace. With that we | |
// can see where in the code app.debug() is called from. | |
// Firebug/etc will just show the line #15 in this file as the caller. | |
var e = new Error('stack trace helper error'); | |
var stack = e.stack.split('\n'); | |
var file = stack[1].substr(stack[1].indexOf("http"), stack[1].length); | |
// Log message, with styling | |
console[level]("%c" + message + "%c" + file, messageStyle, fileStyle); | |
} else { | |
// Otherwise fall back to debug level | |
console.debug(message); | |
} | |
} | |
} | |
}; | |
app.debug('This is your final notice!'); | |
app.debug('You have been warned!', 'warn'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment