1

I'd like to use a modified version of this solution, to wrap console logging into a new function:

function Logger(force) {

    const logging = {};

    if (force) {
        for (let m in console) {
            if (typeof console[m] == 'function') {
                logging[m] = console[m].bind(console);
            }
        }
    } else {
        for (let m in console) {
            if (typeof console[m] == 'function') {
                logging[m] = function() {};
            }
        }
    }

    return logging;
}

debugOff = new Logger(false);
debugOff.log("this WILL NOT log");


debugOn = new Logger(true);
debugOn.log("This WILL log");

However, I'd like to not create a new instance of the Logger, and just pass true/false with the relevant string. I've tried wrapping the new instance in another function, but I'm having to use a specific method in it:

function noopLogger (force, string) {

    function Logger(force) {

        const logging = {};

        if (force) {
            for (let m in console) {
                if (typeof console[m] == 'function') {
                    logging[m] = console[m].bind(console);
                }
            }
        } else {
            for (let m in console) {
                if (typeof console[m] == 'function') {
                    logging[m] = function() {};
                }
            }
        }

        return logging;
    }

    instance = new Logger(force);
    return instance.log(string); // don't want to do this here
}

noopLogger(true, "this will log"); // this logs, but I only have access to log, not warn, error, etc.

How can I refactor this so I can call:

noopLogger.log(true, 'this WILL log'); 
noopLogger.log(false, 'this WILL NOT log');
sansSpoon
  • 2,115
  • 2
  • 24
  • 43

1 Answers1

2

I think this fulfills your requirements. Let me know if you are looking for something more or something else.

function getLogger() {
  const logger = {};

  for (let m in console) {
    if (typeof console[m] == 'function') {
        logger[m] = function (force, string) {
          if (!force) return;
          console[m].call(console, string);
        }
    }
  }
  return logger;

}

const noopLogger = getLogger();
noopLogger.log(true, 'this WILL log'); 
noopLogger.log(false, 'this WILL NOT log');
noopLogger.warn(true, 'this warning WILL log');
noopLogger.warn(false, 'this warning WILL NOT log');

Output:

:> node test.js
this WILL log
this warning WILL log
Neeraj Sharma
  • 1,067
  • 7
  • 14
  • `logger[m] = function (force, string)` is the expression that was eluding me. I was getting hung up on the binding. That's very much @Neeraj Sharma – sansSpoon Mar 18 '18 at 23:44