Lazy logging evaluation in JS?

68 Views Asked by At

Is there a way to do lazy evaluation when logging?

For instance console.log("Result: ", throwingFunc()) won't log the first argument ("Result: "), as the 2nd argument, throwingFunc(), will get evaluated before the call to console.log(..).

I also tried logger.debug("Result: ", () => throwingFunc()) with log4js and other libraries, but to my surprise none of them worked...

1

There are 1 best solutions below

3
KooiInc On

You can check the logger functions' arguments and when one or more of them are function and do a trial run of them before logging. Something like:

const throwingFunc = () => {throw new Error(`thrown something`);};
const someMsg = () => `that worked!`;
const logger = (...args) => {
  const tryFn = fn => {
    try { return fn(); }
    catch(err) { return `*${err.message}*`; }
  }
  const evaluated = args.map(arg =>
    arg instanceof Function ? tryFn(arg) : arg);
  console.log(evaluated.join(``)); 
}

logger("Result: ", throwingFunc, `, `, someMsg);