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
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
.
debug.js
:
function debug(msg) {
console.log(msg)
}
main.js
function main() {
debug('Hello world!') // debug() in debug.js
}
The current behavior:
Hello world! ... debug.js:2
The behavior I want:
Hello world! ... main.js:3
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?
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:
debug.js:
function debug() {
return function(msg) { console.log(msg) }
}
main.js:
function main() {
debug()('Hello world!')
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With