15

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?

Kristof Degrave
  • 4,142
  • 22
  • 32
  • 1
    Nah, the `args` variable should be garbage-collected after `log` is executed, shouldn't need to be set to `null`. Yet, the items of that array are passed on to `console.log`, where they are held forever - possibly your leak if they're complex host objects like database transactions. Or, `.apply` leaks when called on `console` methods, in which browser did you test that? – Bergi Oct 21 '12 at 11:52
  • You don't set the `arguments` reference to null, but the `args` variable? – Bergi Oct 21 '12 at 11:54
  • I know, but that doesn't make a difference. My leak is solved when I set arguments to null, but I can't do that because it isn't allowed in strict mode. my findings come from google chrome – Kristof Degrave Oct 21 '12 at 14:46
  • The only place in your code where a memory leak could be introduced is the `currentTime` function but it should get GC'd when the `log` function returns. Try `var currentTime = function () { ... }` but it's a long shot. It should not make any difference. – J. K. Oct 21 '12 at 19:15
  • @Ian Kuca: tnx for the suggestion, but didn't make any difference. I'm certain that it is the "argmunents" attribute of the function who is leaking. When I add arguments = null at the end of my function, no extra memory is added to the heap. Without it, if I compare 2 heap snapshots, several objects are added to the heap. – Kristof Degrave Oct 21 '12 at 19:36
  • 1
    Are you sure the GC ran? It can take a few secs. The `arguments` variable is trashed when the function returns thus releasing any references to outside objects it contained. Weird. – J. K. Oct 21 '12 at 19:40
  • I think so. When I call this method multiple times, it keeps increasing my memory. – Kristof Degrave Oct 21 '12 at 19:46
  • Must be another problem I see. arguments = null didn't increase my memory, because it wasn't valid. This way the function wasn't called. It will probably be what Bergi said. Complex objects are held for ever by the console.log method. – Kristof Degrave Oct 21 '12 at 20:01
  • What is your runtime environment? Do you run this in browser or nodejs or something else? – Dmitry Pashkevich Oct 21 '12 at 20:28
  • I am running this in the browser. I don't make use of node.js or other frameworks – Kristof Degrave Oct 21 '12 at 20:30
  • Bergi's right. `console.log` is probably the problem here. Serialize your objects. – J. K. Oct 21 '12 at 23:29

1 Answers1

26

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

Community
  • 1
  • 1
Dmitry Pashkevich
  • 13,431
  • 9
  • 55
  • 73
  • Hi, your explanation sounds logical. I never looked at it that way. Tnx for all your comments. I'm going to add an extra warning when developers enable the logging feature so they are aware of the risk and don't use it in production. – Kristof Degrave Oct 22 '12 at 05:13
  • I typically use a small wrapping function around all logging / debugging tools that just discards all browser logging input if the site is running on the production environment, sometimes with a check for a "debug" query parameter override so I can work with specific users having issues. This avoids memory leaks, reduces the risk of accidentally logging sensitive data, improves performance (at least marginally), and reduces needless concerns from know-enough-to-be-dangerous managers, testers, and users. – brichins Mar 23 '17 at 17:22
  • @brichins this is off-topic, but how do you then troubleshoot issues when your users have them? – Dmitry Pashkevich Mar 23 '17 at 19:41
  • 1
    @DmitryPashkevich There are still analytics running separately so I can get remote error reports. Obviously this isn't an appropriate solution for everyone - I typically work in closed environments, not with sites used by the general public, so if a site is having issues beyond what the analytics can find I can work directly with specific users. I send them (or screen share and take control) to `/?debug`, and the envirionment-sensing script notes the presence of the query parameter `debug` and flips logging & other diagnostic functionality back on. – brichins Mar 24 '17 at 19:52