我可以在 javascript 中扩展控制台对象(用于重新路由日志记录)吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9277780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I extend the console object (for rerouting the logging) in javascript?
提问by prefabSOFT
Is it possible to extend the console object?
是否可以扩展控制台对象?
I tried something like:
我试过类似的东西:
Console.prototype.log = function(msg){
Console.prototype.log.call(msg);
alert(msg);
}
But this didn't work. I want to add additional logging to the console object via a framework like log4javascriptand still use the standard console object (in cases where log4javascript is not available) in my code.
但这没有用。我想通过像log4javascript这样的框架向控制台对象添加额外的日志记录,并且仍然在我的代码中使用标准控制台对象(在 log4javascript 不可用的情况下)。
Thanks in advance!
提前致谢!
回答by Sergey Ilinsky
Try following:
尝试以下操作:
(function() {
var exLog = console.log;
console.log = function(msg) {
exLog.apply(this, arguments);
alert(msg);
}
})()
回答by Mike Gleason jr Couturier
Use the proxy pattern, see my answer for a similar case:
使用代理模式,请参阅我对类似案例的回答:
JavaScript: Overriding alert()
Hope this helps
希望这可以帮助
回答by nitesh singh
You Can Also add log Time in This Way :
您还可以通过这种方式添加日志时间:
added Momentjs or use New Date()instead of moment.
添加 Momentjs 或使用New Date()而不是 moment。
var oldConsole = console.log;
console.log = function(){
var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
Array.prototype.unshift.call(arguments, timestamp);
oldConsole.apply(this, arguments);
};
回答by ekerner
// console aliases and verbose logger - console doesnt prototype
var c = console;
c.l = c.log,
c.e = c.error,
c.v = c.verbose = function() {
if (!myclass || !myclass.verbose) // verbose switch
return;
var args = Array.prototype.slice.call(arguments); // toArray
args.unshift('Verbose:');
c.l.apply(this, args); // log
};
// you can then do
var myclass = new myClass();
myclass.prototype.verbose = false;
// generally these calls would be inside your class
c.v('1 This will NOT log as verbose == false');
c.l('2 This will log');
myclass.verbose = true;
c.v('3 This will log');
I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.
我注意到上面 nitesh 对 Array.prototype.unshift.call 的使用是添加 'Verbose:' 标签的更好方法。
回答by eds1999
It's really the same solution some others have given, but I believe this is the most elegant and least hacky way to accomplish this. The spread syntax (...args) makes sure not a single argument is lost.
这确实与其他一些人给出的解决方案相同,但我相信这是实现这一目标的最优雅、最简单的方法。展开语法 (...args)确保不会丢失单个参数。
var _console={...console}
console.log = function(...args) {
var msg = {...args}[0];
//YOUR_CODE
_console.log(...args);
}
回答by Amin NAIRI
For ECMAScript 2015 and later
对于 ECMAScript 2015 及更高版本
You can use the newer Proxyfeature from the ECMAScript 2015standard to "hiHyman" the global console.log.
您可以使用ECMAScript 2015标准中较新的代理功能来“劫持”全局console.log。
Source-Code
源代码
'use strict';
class Mocker {
static mockConsoleLog() {
Mocker.oldGlobalConsole = window.console;
window.console = new Proxy(window.console, {
get(target, property) {
if (property === 'log') {
return function(...parameters) {
Mocker.consoleLogReturnValue = parameters.join(' ');
}
}
return target[property];
}
});
}
static unmockConsoleLog() {
window.console = Mocker.oldGlobalConsole;
}
}
Mocker.mockConsoleLog();
console.log('hello'); // nothing happens here
Mocker.unmockConsoleLog();
if (Mocker.consoleLogReturnValue === 'hello') {
console.log('Hello world!'); // Hello world!
alert(Mocker.consoleLogReturnValue);
// anything you want to do with the console log return value here...
}
Online Demo
在线演示
复制它。
Node.js users...
Node.js 用户...
... I do not forget you. You can take this source-code and replace window.console
by gloabl.console
to properly reference the console object (and of course, get rid of the alert
call). In fact, I wrote this code initially and tested it on Node.js.
... 我不会忘记你。您可以使用此源代码并替换window.console
为gloabl.console
以正确引用控制台对象(当然,摆脱alert
调用)。事实上,我最初编写了这段代码并在 Node.js 上对其进行了测试。