4

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.

Behnam Azimi
  • 2,260
  • 3
  • 34
  • 52

1 Answers1

0

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)
}
gui3
  • 1,711
  • 14
  • 30
  • 1
    REM : this will not work if you call functions from files in events or in the console or asynchronously, but it gives you the right file if console.log is called at the loading of the script – gui3 Jul 24 '20 at 18:39