Search code examples
javascriptnode.jswinston

Nodejs console overload scope issue


I am trying to override the console in Nodejs with Winston.

for (var z in loggerSettings) {
    console[z] = (function () {
        var i = z + ''
          , _backup = console[z];
        return function () {
            var utfs = arguments.length >= 2 ? util.format.apply(util, arguments) : arguments[0]
              , coldex = 0;
            if (true) logger[i == 'log' ? 'info' : i](utfs);
            if (loggerSettings[i].console){
                if ((coldex = utfs.indexOf(']') + 1) <= MAX_TAG_LENGTH) 
                    _backup(utfs.substring(0, coldex)[i]['inverse'] + utfs.substring(coldex));
                else _backup(utfs);
            }
        }
    })();
}

Here var z is just a the basic console.log, console.info, console.warn methods. The issue is z is changing for each of the anonymous function. It is a bit challenging to address the problem, but the scope of z seems to change and the variable z is not exactly sticking to a constant value for each iteration of the loop. Z doesn't want to stick to its scope.


Solution

  • Javascript has function scope, but no block scope, meaning that every reference to z in your console-functions will use the last value of z.

    If you want 'z' to stick, pass it as an argument to an anonymous function:

    for (var z in loggerSettings) {
      (function(z) {
        console[z] = (function () {...});
      )(z);
    };