Print debugging output only if some condition holds

I want to introduce some checks in my function. In my real code, the check is time-consuming.
So, I want that part to run only when some global environment variable is set (e.g. ENV["JULIA_DEBUG"] = "all").
When the global variable is not set (e.g. ENV["JULIA_DEBUG"] = ""), I will assume that the condition is met and skip the check.

An example is the following.

function my_func(a::Int)
    @debug begin
        # Perform a time-consuming check here.
        # This is a simplified example.
        check = a + 2 < 0
        check ? "" : "a + 2 cannot be negative"
    end
    # Perform real calculation here.
    return a
end

Calling my_func(-5) writes Debug: a cannot be negative output, which is what I want.

But my_func(5) also writes Debug: to the log, which is what I do not want.
Can I make the code be completely silent in this case?

@debug (and other logging macros like @info & co) are meant to log messages, so I’m not sure that’s what you want here.

The standard @assert is closer to what you’d want, but AFAIK it is not so easy to control whether checks are actually performed at run-time or not. So in your case, I’d probably use something like ToggleableAsserts – see the relevant discussion about this here on discourse:

You example could be written something like (untested):

using ToggleableAsserts

function my_func(a::Int)
    @toggled_assert (a + 2 < 0)  "a + 2 cannot be negative"
    # Perform real calculation here.
    return a
end

And you can call toggle(true) or toggle(false) to decide whether you want checks to actually be performed (debug mode) or be elided (performance mode)

1 Like