Answers for "Line logger"

0

Line logger

const STACK_LINE_REGEX = /(\d+):(\d+)\)?$/;

function lineLogger(...log) {
  let err;

  try {
    throw new Error();
  } catch (error) {
    err = error;
  }

  try {
    const stacks = err.stack.split('\\n');
    const [, line] = STACK_LINE_REGEX.exec(stacks[2]);

    return this(`[${line}]`, ...log);
  } catch (err) {
    return this(...log);
  }
}

lineLogger.call(console.log, 'foobar');
lineLogger.call(console.error, 42);
Posted by: Guest on September-22-2021

Browse Popular Code Answers by Language