Skip to content

Instantly share code, notes, and snippets.

@yyfrankyy
Created May 9, 2011 02:21
Show Gist options
  • Save yyfrankyy/961936 to your computer and use it in GitHub Desktop.
Save yyfrankyy/961936 to your computer and use it in GitHub Desktop.
Overwrite Global Console
// overwrite global console based on kissy
//
// chrome 的 console 不能转移this,即不能call或者apply到其他分组上
// http://code.google.com/p/chromium/issues/detail?id=48662
// http://stackoverflow.com/questions/5133649/alias-to-chrome-console-log
//
// firefox 不能覆写console对象,只定义了Getter,直接覆盖方法属性
//
// 注意有些方法不完全兼容
// 比如console.profile/profileEnd在IE的表现跟
// Webkit DevTools/Firebug的表现不一致
// 所以后续有一次try/catch
//
// http://twitter.com/yyfrankyy/status/65769142648717312
var S = KISSY,
global = S.__HOST,
_cslCache = [],
origin_csl = global.console || {},
global_csl = {},
_csl = {};
// copy all console function into a new object
S.each(origin_csl, function(method, i) {
var log = [i, method];
_cslCache.push(log);
global_csl[log[0]] = log[1];
});
// TODO move this into event.
var debugStyle = {
'rule': 'color: green',
'form': 'background: #d5ffc4',
'monitor': 'color: #0c2d75',
'realPay': 'color: red; font-weight: bold; text-align: right'
};
// reset for all console methods;
S.each(['assert', 'count', 'debug', 'dir', 'dirxml', 'error',
'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'memory', 'profile', 'profileEnd',
'profiles', 'time', 'timeEnd', 'trace', 'warn'],
function(method) {
if (S.UA.ie && S.UA.ie < 8) {
_csl[method] = !S.isEmptyObject(origin_csl) ?
origin_csl.log : function() {
/*ignore*/
};
return;
}
_csl[method] = function() {
var bind = Function.prototype.bind,
args = [].slice.call(arguments),
trace = '',
prefix = '';
if (!(global_csl && S.Config.debug) || !bind) return args[0];
if (!(method in global_csl)) {
prefix = '[' + method.toUpperCase() + '] ';
method = 'log';
args[0] = prefix + args[0];
}
// firebug可以用css
if (S.UA.firefox) {
for (var i in debugStyle) {
if (!(new RegExp('^\\[' + i + '\\]')
.test(args[0]))) continue;
var lc = '%c' + args.shift();
args.unshift(lc, debugStyle[i]);
break;
}
}
_csl.fire('BeforeLog', {args: args});
// 设置log过滤器
if (!(!origin_csl.filter || bind.call(
origin_csl.filter,
origin_csl
).apply(origin_csl, args))) return args[0];
try {
bind.call(
global_csl[method],
origin_csl
).apply(origin_csl, args);
} catch (e) {}
return args[0];
};
});
S.mix(_csl, S.EventTarget);
// exclude loaded logs
_csl.filter = function(arg) {
return !(/(loaded\.)$/.test(arg) || /^(standard)/.test(arg));
};
S.each(_csl, function(fn, i) {
origin_csl[i] = fn;
});
global.console = _csl;
// }}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment