Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak when logging complex objects

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?

like image 301
Kristof Degrave Avatar asked Oct 21 '12 08:10

Kristof Degrave


1 Answers

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

like image 119
Dmitry Pashkevich Avatar answered Oct 12 '22 13:10

Dmitry Pashkevich