javascript - Is it possible to bind a date/time to a console log? -
i have following code:
var mylog = console.log.bind(console, '[debug]');
which works find when want log things prepended [debug]
console. want add date/time log , tried this:
var mylog = console.log.bind(console, '[debug ' + (new date) + ']');
which not work because always logs same time (the time .bind
called).
is there way (using .bind
) log current time on each log without having this:
var mylog = function(){ var args = ['[debug ' + (new date) + ']']; for(var = 0; < arguments.length; ++i) { args.push(arguments[i]); } return console.log.apply(console, args); };
?
because above method shows me line console.log.apply
called , not line mylog
called.
yes. http://jsfiddle.net/swfjg/6/
var debug = (function(){ var timestamp = function(){}; timestamp.tostring = function(){ return "[debug " + (new date).tolocaletimestring() + "]"; }; return { log: console.log.bind(console, '%s', timestamp) } })(); debug.log("banana", {foo:'bar'}); //[debug 2:43:21 pm] banana object {foo: "bar"} console.log("peppercorn"); //peppercorn debug.log("apple"); //[debug 2:43:21 pm] apple debug.log("orange"); //[debug 2:43:21 pm] orange settimeout(function(){ debug.log("mango"); //[debug 2:43:25 pm] mango },3000)
this works because tostring
called on timestamp
(and, in fact, everything) each time console.log
called.
we overwrite default tostring
method, , replace time stamp (obviously can change output whatever want).
i chose above pattern because, others have noted (in chat), can extend debug object other things.
... return { log: console.log.bind(console, '%s', timestamp), error: console.error.bind(console, '%s', timestamp), info: console.info.bind(console, '%s', timestamp), warn: console.warn.bind(console, '%s', timestamp), group: ..., groupend: ..., groupcollapsed: ... // etc } ...
Comments
Post a Comment