Skip to content

Instantly share code, notes, and snippets.

@yangfch3
Last active December 19, 2017 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yangfch3/407fc0297fac43948cbd5b9e819ff0ef to your computer and use it in GitHub Desktop.
Save yangfch3/407fc0297fac43948cbd5b9e819ff0ef to your computer and use it in GitHub Desktop.
一段原生 console 对象增强示例代码
var console = function() {
// 存储旧 console 地址
var oldConsole = window.console;
// 增强函数用到的一些配置
var colors = ["#eaeaea", "#b7b7b7"];
var index = 1;
window.newConsole = {
wc: oldConsole
};
// 用于增强函数
function logOnPage(msg, item) {
var myConsoleBox = document.getElementById('myDebugInfo');
if (myConsoleBox === null) {
myConsoleBox = document.createElement('ol');
myConsoleBox.id = 'myDebugInfo';
myConsoleBox.style.background = '#dedede';
myConsoleBox.style.border = '1px solid sliver';
myConsoleBox.style.padding = '5px';
myConsoleBox.style.paddingLeft = '20px';
myConsoleBox.style.margin = "0";
myConsoleBox.style.width = '200px';
myConsoleBox.style.position = 'fixed';
myConsoleBox.style.right = '0px';
myConsoleBox.style.top = '0px';
myConsoleBox.style.zIndex = '10000';
myConsoleBox.style.height = '273px';
myConsoleBox.style.overflowY = 'scroll';
myConsoleBox.style.wordWrap = 'break-word';
myConsoleBox.style.wordBreak = 'break-all';
document.body.appendChild(myConsoleBox);
}
myConsoleBox.innerHTML += ('<li style="list-style: decimal outside none !important;'
+ 'background-color:'
+ colors[index%2]
+ '">'
+ item + ": "
+ msg
+ '</li>');
index++;
}
// 使用存储的 wc 来还原 console 的各项方法,同时使用增强函数对其进行加强
['log', 'error', 'warn', 'debug', 'info'].forEach(function (item) {
newConsole[item] = function (msg, logOnPageBoolean) {
this.wc[item](msg);
var logOnPageBoolean = logOnPageBoolean === true ? logOnPageBoolean : false;
if (logOnPageBoolean) {
logOnPage(msg, item);
}
};
});
return newConsole;
}();
// 测试代码
console.log("我是一个 log");
console.info("我是一个 info", true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment