If there a way to do a conditional logpoint in Chrome Devtools?
- I KNOW how to add a logpoint or a conditional breakpoint;
- I DON'T KNOW if is there a way to add a conditional logpoint (a logpoint logging only when a specific condition is meet).
If there a way to do a conditional logpoint in Chrome Devtools?
There's no way to add a conditional logpoint in Chrome Devtools.
The workaround is to add a non-breaking conditional breakpoint with console.log
:
foo.bar===123 && console.log('foo!', foo)
The result of this expression is always falsy: either false
(for the condition) or undefined
(for console.log) so the breakpoint doesn't trigger and only prints the message on condition.
What I have been doing is creating a log message that throws an error given a specified condition. Any code in the logpoint that throws prevents the log from making it to the console but will not have an effect the original, running code. You can abuse this to make what is effectively a conditional logpoint with a format such as:
<condition> ? <message to log> : <expression that throws>
For example:
this.enabled ? `Enabled sproket's name is ${this.name}` : null.x
This will only log "Enabled sproket's name is ..." if the enabled
property is true. If not, the logpoint will evaluate null.x
which throws, preventing anything from getting logged at all.
If the goal is to reduce the noise in the console, you can tag the useful/interesting messages with some text, and set the console filter to show only the one's you want... Not great; would be better if the condition in the 'conditional breakpoint' was applied to the logpoint
if you want breaking conditional Logpoint:
the way to do it is to add a breaking conditional breakpoint with console.log
foo && (console.log('foo!'), foo)
simply said, it triggers the breakpoint and logs only if foo exits.
let foo = false // or null or undefined
false
// (doesn't trigger the breakpoint)
let foo = true
foo!
true
// (logs 'foo!' in console and triggers the breakpoint)
I'm debugging TypeScript code, which I see in Chrome Dev Tools with help of source maps, and answers above work, but compiler also compiled code in breakpoint from console.log
into lgs.log
, thus needed to specify window.console.log
:
somethingILookFor === true && window.console.log(`Current value: ${someValue}`)
© 2022 - 2024 — McMap. All rights reserved.