2

I have a helper function that prepends some message when calling console.log:

function log(...arg: any[]): void {
  const LOG_PREFIX = `[file.ts]`;
  // 1. Convert args to a normal array
  const args: any[] = Array.prototype.slice.call(arguments);
  // 2. Prepend log prefix log string
  args.unshift(LOG_PREFIX);
  // 3. Pass along arguments to console.log
  console.log.call(console, ...args);
}

The problem is that when it logs, the console shows a clickable link to this log:8 or the line that calls console.log.call(console, ...args)

Is there a way I can adjust this method so that it keeps the intended stack trace of where i call this method instead?

1
  • This looks like typescript not javascript...I think it's not possible change stack trace. also since you have an array of arguments, its probably better use apply() instead of call(), in which case you can achieve the same thing with one-liner: console.log.apply(console, ["[file.ts]", ...arg]); Commented Jun 14, 2022 at 2:38

1 Answer 1

3

There you go, Function.prototype.bind() is to the rescue:

const log = console.log.bind(window.console, "[file.ts]");

log("test", "blah");
console.log("test", "blah");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.