这里的答案都没有考虑传递多个参数的控制台消息。例如。 console.log("Error:", "error details"))。
替换默认日志函数的函数更好地考虑所有函数参数(例如,通过使用arguments 对象)。这是一个例子:
console.log = function() {
log.textContent += Array.prototype.slice.call(arguments).join(' ');
}
(Array.prototype.slice.call(...) 只是将arguments 对象转换为数组,因此可以轻松地与join() 连接。)
当原始日志也应该保持工作时:
console.log = (function (old_log, log) {
return function () {
log.textContent += Array.prototype.slice.call(arguments).join(' ');
old_log.apply(console, arguments);
};
} (console.log.bind(console), document.querySelector('#log')));
一个完整的解决方案:
var log = document.querySelector('#log');
['log','debug','info','warn','error'].forEach(function (verb) {
console[verb] = (function (method, verb, log) {
return function () {
method.apply(console, arguments);
var msg = document.createElement('div');
msg.classList.add(verb);
msg.textContent = verb + ': ' + Array.prototype.slice.call(arguments).join(' ');
log.appendChild(msg);
};
})(console[verb], verb, log);
});
(使用多个参数发出消息的框架的一个示例是 Video.js。但当然还有很多其他的。)
编辑:多个参数的另一个用途是控制台的格式化功能(例如console.log("Status code: %d", code)。
关于未显示的错误
(2021 年 12 月更新)
如果任何代码因未捕获的错误而崩溃,则 in 可能不会显示在 div 中。如果可能的话,一种解决方案可能是将所有代码包装在 try 块中以捕获此类错误并将它们手动记录到 div。
try {
// Code that might throw errors...
} catch(err) {
// Pass the error to the overridden error log handler
console.error(err);
}