Using @logmsg with begin/end blocks

Is it somehow possible to do this:
@debug "Results of my calculations: " A=1:100 B=(1:100).*10

In block form, meaning something like this:

@debug begin
    ## Do some stuff:
    A = 1:100
    B = A .* 10
    
    ## Create message
    "Results of my calculations: " A=A B=B
end

which is much more readable when I want to do some more complicated calculations in debug mode?

I’m aware of this question, but I want the calculations to be performed only when the log level is actually set to debugging, which I am not sure the macro posted in that thread does.

Thanks!

You could call @debug like a function:

@debug("Results of my calculations:",
    A = 1:100,
    B = A .* 10,
)

The code inside the parentheses won’t be evaluated if debugging is off. Try:

expensive_calculation() = begin sleep(3); return 1:100 end

# Returns immediately:
@debug("Results of my calculations:",
    A = expensive_calculation(),
    B = A  .* 10,
)

# Runs the expensive code:
ENV["JULIA_DEBUG"] = "all"
@debug("Results of my calculations:",
    A = expensive_calculation(),
    B = A  .* 10,
)

Thanks for your suggestion! But when I run this code, Julia complains that A is not defined:

┌ Error: Exception while generating log record in module Main at REPL[3]:1
│   exception =
│    UndefVarError: `A` not defined

Do you have an idea why? I have not yet taken a deep dive into how Julia’s macros work exactly, maybe I’ll have to do that now :smiley:

Sorry, my bad. I must have had a global A left in the REPL when I tried that.

The log macros iterate over the key value pairs so, A goes out of scope before evaluating B = .... We can’t do more complicated things than A = function_call().

I use something like this in my code, generating a string and feeding it to the macro:

function debug_foo()
   A = 1:100
   B = A .* 10
   """Results of my calculations
      A = $A
      B = $B
   """
end
@debug debug_foo()