console.logCopy = console.log.bind(console);
console.log = function()
{
// Timestamp to prepend
var timestamp = new Date().toJSON();
if (arguments.length)
{
// True array copy so we can call .splice()
var args = Array.prototype.slice.call(arguments, 0);
// If there is a format string then... it must
// be a string
if (typeof arguments[0] === "string")
{
// Prepend timestamp to the (possibly format) string
args[0] = "%o: " + arguments[0];
// Insert the timestamp where it has to be
args.splice(1, 0, timestamp);
// Log the whole array
this.logCopy.apply(this, args);
}
else
{
// "Normal" log
this.logCopy(timestamp, args);
}
}
};
this.log = function() {
var args = [];
args.push('[' + new Date().toUTCString() + '] ');
//now add all the other arguments that were passed in:
for (var _i = 0, _len = arguments.length; _i < _len; _i++) {
arg = arguments[_i];
args.push(arg);
}
//pass it all into the "real" log function
window.console.log.apply(window.console, args);
}
所以你可以使用它:
this.log({test: 'log'}, 'monkey', 42);
输出如下所示:
[Mon, 11 Mar 2013 16:47:49 GMT]对象{test: "log"} monkey 42
console.logCopy = console.log.bind(console);
console.log = function()
{
if (arguments.length)
{
var timestamp = new Date().toJSON(); // The easiest way I found to get milliseconds in the timestamp
var args = arguments;
args[0] = timestamp + ' > ' + arguments[0];
this.logCopy.apply(this, args);
}
};
function logf() {
// console.log is native function, has no .bind in some browsers.
// TODO: fallback to wrapping if .bind doesn't exist...
return Function.prototype.bind.call(console.log, console, yourTimeFormat());
}