计算console.log对象

时间:2016-12-15 15:03:25

标签: javascript json

下面的代码将控制台日志打印到页面上。它记录来自服务器的获取和响应,如:

14:15:17 GMT+0000 (GMT Standard Time) Submitting HTTP GET request to http...
14:15:22 GMT+0000 (GMT Standard Time) Received HTTP response: {..
14:15:17 GMT+0000 (GMT Standard Time) Submitting HTTP GET request to http...
14:15:22 GMT+0000 (GMT Standard Time) Received HTTP response: {..

我不想在页面上显示这些内容,而是计算每个响应和请求,以便您看到一个从1开始并在结束时结束的数字,可以是任何数字。这是为了向用户显示正在发生的事情而不向他们显示所有响应并获取数据。

        function logHttpResponse(response) {
        var now = new Date();
        var logger = document.getElementById('log');
        var logMessage = now.toTimeString() + " Received HTTP response: " + JSON.stringify(response);
        console.log = function (logMessage) {
            if (typeof logMessage == 'object') {
                logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(logMessage) : String(logMessage)) + '<br />';
            } else {
                logger.innerHTML += logMessage + '<br />';
            }
        }
    }

和html:

<div id="log"></div>

3 个答案:

答案 0 :(得分:2)

如果您只想覆盖console.log来打印回复计数,则应该这样做,但这会增加任何console.log来电的计数。

var logCount = 0

console.log = function (logMessage) {
    var logger = document.getElementById('log');
    logCount++;
    logger.innerHTML = logCount;
}

如果您想依靠响应而不是所有控制台日志,请使用类似

的内容
var logCount = 0

function logHttpResponse(response) {
    var logger = document.getElementById('log');
    logCount++;
    logger.innerHTML = logCount;
}

答案 1 :(得分:1)

我的问题并不完全清楚,但据我所知,您正在尝试报告每个打开的http请求的状态。我建议你用一个像这样计算的函数来包装你的请求:

var globalCounter = 1;
function performHttpRequest(requestUrl) {
    // Store a local copy of the counter for this request
    var currentCounter = globalCounter++;

    // Log to the user in whatever way you see fit
    // Could also for instance be with an array of status objects
    logger.innerHTML += 'now starting request ' + currentCounter + '</br>';

    // Perform the async request using the framework you prefer
    return $http.get(requestUrl)
        .then(function(result) {
            // When the async request finishes, update the log with the counter
            // we saved earlier
            logger.innerHTML += 'request ' + currentCounter + ' finished</br>';

            // Make sure to return the result of the action to the calling
            // function.
            return result;
        });
}

上面的示例使用Angular作为执行实际http请求的框架,但它也适用于jQuery或任何其他框架。

答案 2 :(得分:1)

您可以PerformanceObserver使用entryTypes设置为"resource"。在回调.getEntries()的第一个参数上调用PerformanceObserverEntryList,使用for..of循环迭代条目对象。在条目对象上调用.toJSON(),将对象传递给Object.entries()以迭代每个属性,嵌套for..of循环中当前条目对象的值。

const observer = new PerformanceObserver((list, obj) => {
  for (let entry of list.getEntries()) {
    for (let [key, prop] of Object.entries(entry.toJSON())) {
      logger.innerHTML += ` ${key}:${prop} `;
    }
  }
});

observer.observe({
  entryTypes: ["resource"]
});