最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Count console.log objects - Stack Overflow

programmeradmin0浏览0评论

The code below prints the console log onto the page. It logs gets and responses from server like:

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: {..

Instead of displaying these onto the page I would like to count every response and request so you see a a number starting at 1 and ending when it ends, could be any number. This is to show the user that something is happening without showing them all the response and get data.

        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 />';
            }
        }
    }

and html:

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

The code below prints the console log onto the page. It logs gets and responses from server like:

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: {..

Instead of displaying these onto the page I would like to count every response and request so you see a a number starting at 1 and ending when it ends, could be any number. This is to show the user that something is happening without showing them all the response and get data.

        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 />';
            }
        }
    }

and html:

<div id="log"></div>
Share Improve this question edited Dec 19, 2016 at 11:00 ntalbs 29.5k8 gold badges70 silver badges85 bronze badges asked Dec 15, 2016 at 15:03 Tom RudgeTom Rudge 3,2729 gold badges55 silver badges103 bronze badges 3
  • 1 You are assigning to console.log every time logHttpResponse is called. For one thing I don't think you should re-assign console.log but regardless, you should only do it once outside the function (and pass logger in as closure argument). – Tatsh Commented Dec 15, 2016 at 15:10
  • 1 What's stopping you (after doing what Tatsh suggests) from putting a counter into your closure like you've closed over logMessage? – Mike Cluck Commented Dec 15, 2016 at 15:11
  • What if you define a variable outside the logHttpResponse() function, and increase that with 1 inside the function. You can set that in logMessage . – Manoj Lodhi Commented Dec 19, 2016 at 11:05
Add a ment  | 

3 Answers 3

Reset to default 3 +25

If you just want to override console.log to print the count of responses, this should do it, but this will increment the count for any console.log call.

var logCount = 0

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

If you want to count on responses and not all console logs, use something like this

var logCount = 0

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

Your question is not entirely clear to me, but from what I understand is that you're trying to report on the status of each open http request. I'd suggest you wrap your request with a function that does the counting like this:

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;
        });
}

The example above uses Angular as the framework to perform the actual http request, but it would just a as well work on jQuery or any other framework.

You can use PerformanceObserver with entryTypes set to "resource". Call .getEntries() on first parameter at callback PerformanceObserverEntryList, iterate entries object with for..of loop. Call .toJSON() on entry object, pass object to Object.entries() to iterate each property, value of current entry object within nested for..of loop.

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"]
});
发布评论

评论列表(0)

  1. 暂无评论