我为此编写了一个简单的跨浏览器库,名为console.history。它在 GitHub 上可用:
https://git.io/console
该库的基本作用是捕获对console.[log/warn/error/debug/info] 的所有调用并将它们存储在console.history 数组中。作为奖励,还添加了完整的堆栈跟踪。
测试文件test.js 包含:
function outer() {
inner();
}
function inner() {
var array = [1,2,3];
var object = {"foo": "bar", "key": "value"};
console.warn("Something went wrong, but we're okay!", array, object);
}
outer();
console.history 的条目将是:
{
"type": "warn",
"timestamp": "Thu, 01 Sep 2016 15:38:28 GMT",
"arguments": {
"0": "Something went wrong, but we're okay!",
"1": [1, 2, 3],
"2": {
"foo": "bar",
"key": "value"
}
},
"stack": {
"0": "at inner (http://localhost:1337/test/test.js:6:11)",
"1": "at outer (http://localhost:1337/test/test.js:2:3)",
"2": "at http://localhost:1337/test/test.js:9:1"
}
}