Search code examples
javascriptweb-component

automating / overriding / extending prefix in console.log for debugging


Anyone have a good solution to extending console.log so that it auto prints class name and method as a prefix? I'm using web components and use strict is turned on.

someFunction() {
  let varA = "hello"
  console.log(this.constructor.name, "someFunction", {varA})
}

Would like to automate this part: this.constructor.name, "someFunction", ...

arguments.callee.name will print the function name, but no longer works with strict mode turned on. Extending console.log in a centralized location via:

export var log = function(){
  var args = Array.prototype.slice.call(arguments);
  args.unshift(this.constructor.name + ": ");
  console.log.apply(console, args);
}

does not work as this.constructor.name does not print the correct context and if it's not in a web component, it doesn't work at all.
Extending console.log in each web component defeats the purpose (or half of it). Could fold a function that extends console.log in the build for each web component but would still have the problem of not being able to call arguments.calleee. Using lit-element, but this is a native javascript issue.


Solution

  • so based on sean-7777's answer, I suppose we could slice the stack output like this:

    let funcname = new Error().stack.split('\n')[1];
    funcname=funcname.slice(funcname.indexOf("at ")+3, funcname.indexOf(" ("));
    console.log(debugline, 'debug text');
    

    If you put it into a helper function, you could just grab line index 2 (since index 1 would give you the name of the helper function).

    I was hoping for something a little more straightforward but hacking the output does work.

    UPDATE:

    export function prtfun() {
      let debugline = new Error().stack.split('\n')[2];
      return debugline.slice(debugline.indexOf("at ")+3, debugline.indexOf(" ("));
    }
    

    call it from anywhere like this: console.log(prtfun(), 'log text...');

    and it will print ClassName.FunctionName log text...

    Works great. I'd disable this in production though.