Skip to content

Instantly share code, notes, and snippets.

@wsd1
Created April 15, 2019 02:09
Show Gist options
  • Save wsd1/7a5eee21a896a26be89e50f3d7d9a123 to your computer and use it in GitHub Desktop.
Save wsd1/7a5eee21a896a26be89e50f3d7d9a123 to your computer and use it in GitHub Desktop.
浏览器 console对象的兼容性包装和缓存化处理
// console.log/warn/error/info 均可用
// console.log('ha', 'hi');
// console.show(false); //停止显示log
// console.save(true); //开始存储log
// logs = console.cache(); //获取log数组,并清空log缓存
window.console = (function (origConsole) {
if (!window.console || !origConsole) {
origConsole = {};
}
var isDebug = true, isSaveLog = false,
logArray = {
logs: [],
errors: [],
warns: [],
infos: []
};
function showDate(){
var date = new Date(),
str = date.toTimeString();
return str;
}
return {
log: function () {
[].unshift.call(arguments, `[${(new Date()).toTimeString()}]`);
isDebug && origConsole.log && origConsole.log.apply(origConsole, arguments);
this.addLog(arguments, "logs");
},
warn: function () {
[].unshift.call(arguments, `[${(new Date()).toTimeString()}]`);
isDebug && origConsole.warn && origConsole.warn.apply(origConsole, arguments);
this.addLog(arguments, "errors");
},
error: function () {
[].unshift.call(arguments, `[${(new Date()).toTimeString()}]`);
isDebug && origConsole.error && origConsole.error.apply(origConsole, arguments);
this.addLog(arguments, "warns");
},
info: function (v) {
[].unshift.call(arguments, `[${(new Date()).toTimeString()}]`);
isDebug && origConsole.info && origConsole.info.apply(origConsole, arguments);
this.addLog(arguments, "infos");
},
show: function (bool) {
isDebug = bool;
},
save: function (bool) {
isSaveLog = bool;
},
addLog: function (arguments, array) {
if (!isSaveLog) {
return;
}
logArray[array || "logs"].push([].join.call(arguments, ' '));
},
cache: function () {
var old = logArray;
logArray = {};
return old;
}
};
}(window.console));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment