Override console.log method without losing the original stack - javascript

Viewed 213

Here is my logger.js:

const _nativeLog = console.log;
console.log = function (...args) {

  // doing something else in log method

  _nativeLog.apply(this, args)
}

After this code, all logs in console sims to be triggered by my logger.js file. And it's normal because I fire the _nativeLog method inside logger.js.

Here is the output:

enter image description here

My question is that is it possible to keep the original filename that calls the overridden console.log method and show it as origin in the console.

1 Answers

found this How might I get the script filename from within that script?

it's kind of ugly and I'm really not sure if it will give you what you want, but you could try this :

const _nativeLog = console.log;
console.log = function (...args) {

  // ... doing something else in log method

  let scripts = document.getElementsByTagName('script') // get all scripts loaded
  let file= scripts[scripts.length-1].src // get the last loaded script source

  let text = args[0]
  args[0] = file + " \n " + text

  _nativeLog.apply(this, args)
}
Related