Every time I start a new project, I want to pull in a log
function that allows the same functionality as the console.log
, including the full functionality of the Console API.
There are a lot of ways to do this, but many are lacking. A common problem with wrapper functions is that the line number that shows up next to the log is the line number of the log function itself, not where log
was invoked. There are also times where the arguments get logged in a way that isn't quite the same as the native function.
This is an attempt to once and for all document the function that I pull in to new projects. There are two different options:
- The full version: Inspired by the plugin in HTML5 Boilerplate. Use this if you are writing an application and want to create a window.log function. Additionally, this will set all the
console
methods to an empty function if they don't exist to prevent errors from accidentalconsole.log
calls left in your code. Put this snippet at the top of the rest of your scripts - it will need to be evaluated first thing to work. - The portable version: Use this if you want to use it inside a plugin and/or don't want to muck with the global namespace. Just drop it at the bottom of your plugin and log away.
log
can be called before the function declaration, and will not add anything to the window namespace or modify the console objects.
View a live demo here: http://jsfiddle.net/bgrins/MZWtG/