Skip to content

Instantly share code, notes, and snippets.

@erikeldridge
Created April 16, 2011 08:49
Show Gist options
  • Save erikeldridge/922988 to your computer and use it in GitHub Desktop.
Save erikeldridge/922988 to your computer and use it in GitHub Desktop.
A cross-browser logging util
/**
* Cross-browser logging utils
*
* This fn differs from something like the jQuery log plugin in that
* it returns console.log, if avail, instead of calling it. This allows
* us to call it in file with the log statement, which means that the
* line # and file name displayed are more helpful. This isn't supposed
* to be a logging framework like blackbird or log4javascript.
*
* Usage: var msg = 'foo'; log(msg).call(console, msg)
*
* Requires: jQuery event firing. Swapping in another lib would be trivial
*
* Run this code on JS Bin http://jsbin.com/iyeki4/10
*
* @return a noop function if console is undefined
* @return console.debug or console.log otherwise
*/
var log = function(){
// Fire event for non-console logging
var eventName = 'log';
$('body').trigger(eventName, arguments);
// Return noop fn so caller can always call .call() or .apply()
if(!window.console){
return function(){};
}
// Prefer .debug, which displays file name & line #.
var logger = console.debug ? console.debug : console.log;
return logger;
};
module('log util');
// Here's a QUnit test for it
(function(){
test('log fires event', function(){
expect(2);
$(document).delegate('body', 'log', function(e, args){
ok('foo' === args[0], '1st arg should be foo');
ok('bar' === args[1], '2nd arg should be bar');
start();
});
var msg = ['foo', 'bar'];
log(msg).call(console, msg);
stop();
});
})();
/**
* Here's another variation on log(), which eliminates the need for
* passing in the msg twice. It adds a boilerplate callback, though,
* which kinda kills it for me. As above, the goal is to call the
* logger in the file containing the log() statement.
*
* Run this on JS Bin http://jsbin.com/upeca3/4
*
*/
var log = function(/* args */){
var eventName = 'log';
$('body').trigger(eventName, arguments);
if(!window.console){
return;
}
var args = [].slice.call(arguments, 1);
var callback = arguments[0];
var logger = console.debug ? console.debug : console.log;
callback(console, args, logger);
};
// test
(function(){
test('log fires event', function(){
expect(3);
$(document).delegate('body', 'log', function(){
ok('bar' === arguments[2], '3rd arg should be bar');
ok('baz' === arguments[3], '4th arg should be baz');
ok('bax' === arguments[4], '5th arg should be bax');
start();
});
log(function(c,m,l){l.call(c,m);}, 'bar', 'baz', 'bax');
stop();
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment