[英]How to extend console.log?
Is there anyway to write a prototype function, or a function that runs whenever console.log
is called? 无论如何,有没有要编写原型函数,或者每当调用console.log
时都会运行的函数? (And grabs the console.log parameter). (并获取console.log参数)。 I am about 100 KB's in for my web-based game server, and have hundreds of console.logs throughout my code. 我的基于Web的游戏服务器大约有100 KB的存储空间,并且在我的代码中有数百个console.log。 I would love to use the console log data and use the information later in a web-based admin panel or whatnot. 我很乐意使用控制台日志数据,并稍后在基于Web的管理面板中使用该信息。
Oh, and I'm Using nodejs and FS . 哦,我正在使用nodejs和FS 。 Writing to a file is no problem, I know how to do that, but just catching the console.log
is the issue. 写入文件没有问题,我知道该怎么做,但是仅捕获console.log
就是问题。 Any idea? 任何想法?
Just replace console.log
with your own function, like this 只需使用您自己的功能替换console.log
,就像这样
// Store the original version, so that you can fall back to it
var originalLogger = console.log,
fs = require("fs"),
writeStream = fs.createWriteStream("logs.txt");
console.log = function () {
// Do your custom logging logic
for (var i = 0; i < arguments.length; i++) {
writeStream.write(arguments[i]);
}
// You can still call the original `console.log`, with all the `arguments`
originalLogger.apply(this, arguments);
}
console.log("Welcome");
You can reset console.log to your custom log function, demo code: 您可以将console.log重置为自定义日志功能,演示代码:
var fs = require('fs');
var util = require('util');
var l = fs.createWriteStream('abc');
console.log = function () {
var args = Array.prototype.slice.call(arguments)
l.write(util.format.apply(util, args));
l.write('\n');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.