Memory leak when logging complex objects

本秂侑毒 提交于 2020-05-08 03:05:02

问题


I am currently busy writting a javascript library. In that library I want to provide some logging about what is going to the console.

function log () {
        if ((window && typeof (window.console) === "undefined") || !enableLogging) {
            return false;
        }

        function currentTime() {
            var time = new Date();
            return time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds() + '.' + time.getMilliseconds();
        }

        var args = [];

        args.push(currentTime());

        for (var i = 1; i < arguments.length; i++) { 
            args.push(arguments[i]);
        }

        switch (arguments[0]) {
            case severity.exception:
                if (window.console.exception) {
                    window.console.exception.apply(console, args);
                } else {
                    window.console.error.apply(console, args);
                }
                break;
            case severity.error:
                window.console.error.apply(console, args);
                break;
            case severity.warning:
                window.console.warning.apply(console, args);
                break;
            case severity.information:
                window.console.log.apply(console, args);
                break;
            default:
                window.console.log.apply(console, args);
        }
        return true;
    }

The code above presents my log function. When called I provide at least a sevirity, a message and optionally some objects (can be DOM objects like IDBTransaction, IDBDatabase, ...).

log(severity.information, 'DB opened', db);

Now the problem I have is that this results in a memory leak. The problem is that the objects that I pass stay in memory by the console.log method. Is there a way to avoid this or clean this up?


回答1:


It's understandable that objects passed to console.log aren't GC'ed because you need to be able to inspect them in developer tools after your code has run. I wouldn't call this a problem at all because that's how it needs to be when you are debugging your application but the production code shouldn't do any console logging.

If you still need to log stuff (or send it somewhere) in production, I would suggest stringifying your object:

console.log(JSON.stringify(db, null, '\t'));  // '\t' to pretty print

The additional bonus here is that you really capture the object's state at the time of logging (while logging an object reference doesn't guarantee that 1).

Since you are trying to log large objects, be aware that doing this will probably decrease performance, so think twice if you want to do it in production.

1 - seems to have been fixed in latest Chrome



来源:https://stackoverflow.com/questions/12996129/memory-leak-when-logging-complex-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!