如何在 JavaScript 中以字符串形式获取 console.log 内容 [英] How to get the console.log content as string in JavaScript
问题描述
我试图在纯 JavaScript 中将 console.log 作为字符串获取.我的输入是一个脚本,不熟悉,想把console.log中的所有消息都收集成一个字符串.
例如:
function doSomething(){console.log("开始");console.log("结束");var consoleLog = getConsoleLog();返回控制台日志;}函数 getConsoleLog(){//如何实现?}警报(做某事());
请注意,我不需要提醒日志 - 这只是测试功能的一个简单示例.我将不得不对日志的内容进行一些操作.
您可以在使用之前覆盖 console.log
方法:
var logBackup = console.log;var logMessages = [];控制台日志 = 函数(){logMessages.push.apply(logMessages, arguments);logBackup.apply(控制台,参数);};
使用 apply
和 arguments
可以保留正确的 console.log
行为,即您可以通过一次调用添加多个日志消息.>
它将把所有新的 console.log
消息推送到 logMessages
数组.
I'm trying to get the console.log as string in pure JavaScript. My input is a script, which I'm not familiar with, and I want to collect all the messages in the console.log into a string.
For example:
function doSomething(){
console.log("start");
console.log("end");
var consoleLog = getConsoleLog();
return consoleLog;
}
function getConsoleLog(){
// How to implement this?
}
alert(doSomething());
Note that I do not need to alert the log - this is just a simple example of testing the functionality. I'll have to do some operations on the log's content.
You could overwrite console.log
method before using it:
var logBackup = console.log;
var logMessages = [];
console.log = function() {
logMessages.push.apply(logMessages, arguments);
logBackup.apply(console, arguments);
};
Using apply
and arguments
preserves the correct console.log
behaviour, i.e. you can add multiple log messages with a single call.
It will push all new console.log
messages to logMessages
array.
这篇关于如何在 JavaScript 中以字符串形式获取 console.log 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!