Sunday, 11 April 2021

JavaScript Change console call stack

Correct Behavior

When I call console.log() directly from a function, the stack (function and file) from which i called is correct in dev-tools console, as expected.

main.js:

function main() {
    // Works correctly
    console.log('Hello from main()!');
}

Console:

Hello from main()!    ...    main.js:3                       

What I want

Now, when I add a second file called debug.js and call console.log from there, the file from where i called is debug.js, which is correct... but I need debug() to log as if it was called in main.js. Somehow I need to modify the caller, stack or trace to fool console.log() it was called from main.js, when it actually was from deubg.js.

Code

debug.js:

function debug(msg) {
   console.log(msg)
}

main.js

function main() {
   debug('Hello world!') // debug() in debug.js
}

Behavior

The current behavior:

Hello world!    ...    debug.js:2

The behavior I want:

Hello world!    ...    main.js:3


from JavaScript Change console call stack

No comments:

Post a Comment