Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 252
tscpp Avatar asked Apr 06 '21 13:04

tscpp


Video Answer


2 Answers

I believe the issue here is that console log is typically executed from wherever it runs. However, if you were to pass back a function that performs the console log, this might work as you'd like it to. Can you try the below code?

Attempt #1

debug.js:

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

main.js:

function main() {
   debug('Hello world!')
}

If that doesn't work, could you try this:

Attempt #2

debug.js:

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

main.js:

function main() {
   debug()('Hello world!')
}
like image 151
Brandon McConnell Avatar answered Oct 21 '22 04:10

Brandon McConnell


As the WHATWG specification says, the output of the console for every function (error, warn, log, etc...) is implementation-specific:

The printer operation is implementation-defined

As it happens, chromium based browsers display the current frame of the callstack (not the full callstack) when printing the result of a console.log, and you won't be able to change this behavior, because this is related to the JavaScript engine (V8 for chromium based browsers), and not customizable through JavaScript code.

The only JavaScript standard that allows you to display the full callstack is console.trace whose specification is here: https://console.spec.whatwg.org/#trace

It will display something like this for your example code:

console.trace in a chromium based browser

like image 39
Guerric P Avatar answered Oct 21 '22 05:10

Guerric P