2010年8月11日 星期三

log() - A lightweight wrapper for console.log

There are a few things that a console.log wrapper can and should do:

Prevent errors if a console isn't around (i.e. IE)
Maintain a history of logs, so you can look in the past if your console is added afterwards (e.g. firebug lite)
Normalize the browser differences in console integration (e.g. when passing multiple arguments into console.log())
For something you type regularly, make it quicker to type for the lazy among us.
But there are a few considerations…

Console.log.apply doesn't handle multiple arguments in Safari 3 or Chrome 1.1

Firebug, Chrome, and Safari have a clearer presentation for strings when inside an array:

More details on how firebug and webkit inspector visually view these things here: http://gist.github.com/466188

Extra features

A reverse-chronological history, accessible as an array at log.history
I have also included (I removed it) a shorthand logargs() function that is useful when you're inside a function and want to know the context and arguments passed in. I use it a lot in ajax callbacks. Worth noting that it uses arguments.callee.caller, which will be deprecated in ECMAScript 5 Strict mode. :( I killed off logargs cuz nobody lurved it like I did. If you want it… pastie.org/1033665
The code:

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
And if you'd like it minified:

window.log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments))}};
Interestingly, the minified version of this script is smaller (262 148 bytes), and arguably more useful, than the minified firebugx.js, which I've covered before. Plus it has one more feature.

Plus Firebug lite?

You got it. This bookmarklet will add firebug lite, and then output the logged history when it's ready:
>>> Fbug Lite+log <<<

Want more power?

After writing this, I worked with Ben Alman on a more comprehensive and robust logging script. It's excellent if you take full advantage of the console API. And you should be aware that Safari 4 and Chrome 2 have most of that API supported. Make full use of it and don't you dare type another alert()!


摘自:http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

沒有留言:

wibiya widget