Code generation for function definitions

Code generation is one way to tackle this problem, as mentioned in the preceding section. What we will do is to build up the syntax of defining the function and then throw that into a loop to define all three logging functions. Here is how the code may look:

for level in (:info, :warning, :error)
lower_level_str = String(level)
upper_level_str = uppercase(lower_level_str)
upper_level_sym = Symbol(upper_level_str)

fn = Symbol(lower_level_str * "!")
label = " [" * upper_level_str * "] "

@eval function $fn(logger::Logger, args...)
if logger.level <= $upper_level_sym
let io = logger.handle
print(io, trunc(now(), Dates.Second), $label)
for (idx, arg) in enumerate(args)
idx > 0 && print(io, " ")
print(io, arg)
end
println(io)
flush(io)
end
end
end
end

The explanation for the preceding code is as follows:

  • As we need to define functions for three logging levels, we have created a loop that goes through a list of symbols: :info, :warning, and :error.
  • Inside the loop, we can see the function name as fn, the label as label, and the constant for log level comparison (such as INFO, WARN, or ERROR) as upper_level_sym.
  • We use the @eval macro to define the logging function, where the fn variables, label, and upper_level_sym are interpolated into the function body.

After running the code in the Julia REPL, all three functions: info!, warning!, and error! should be defined already. For testing, we can call these with three different kinds of loggers.

Let's try info_logger first:

As expected, all messages are logged to the file because info_logger can take messages at any level. Next, let's test error_logger:

In this case, only the error-level message was written to the log file. The error_logger code effectively filtered out any message that is lower than the error level.

Although we are quite satisfied with the resulting code, do we know what actually happened behind the scenes? How do we debug the code that we cannot even see? Let's take a look at this next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.40.177