I’m trying to write a macro to customize the behavior of logging a bit.
Logging · The Julia Language says
_file=string and _line=integer can be used to override the apparent source location of a log message.
This test file illustrates a problem I’m having concerning reporting the line number where the logging is done:
using Logging
ENABLE_MY_LOGGING = false
function with_my_logging(f, level)
global ENABLE_MY_LOGGING
previous = ENABLE_MY_LOGGING
try
ENABLE_MY_LOGGING = level
f()
finally
ENABLE_MY_LOGGING = previous
end
end
macro my_logging(args...)
logargs = [ :_file => __source__.file,
:_line => __source__.line,
:_module => __module__,
# ERROR: LoadError: MethodError: no method matching iterate(::Expr)
# args...
]
:(
if ENABLE_MY_LOGGING isa LogLevel
@logmsg(ENABLE_MY_LOGGING,
"My logging message",
$logargs...)
end
)
end
with_logger(SimpleLogger(stdout, Logging.Debug)) do
with_my_logging(Logging.Debug) do
@my_logging(v1=2, v2="foo")
end
with_my_logging(Logging.Debug) do
@my_logging(foo="bar")
end
end
When I run it
julia logtest.jl
Activating environment at `c:\Users\Mark Nahabedian\.julia\dev\Unification\Project.toml`
┌ Debug: My logging message
│ _file = c:\Users\Mark Nahabedian\.julia\dev\Unification\logtest.jl
│ _line = 36
│ _module = Main
└ @ Main c:\Users\Mark Nahabedian\.julia\dev\Unification\logtest.jl:26
┌ Debug: My logging message
│ _file = c:\Users\Mark Nahabedian\.julia\dev\Unification\logtest.jl
│ _line = 40
│ _module = Main
└ @ Main c:\Users\Mark Nahabedian\.julia\dev\Unification\logtest.jl:26
Note that the reported values of _line are what I expect, not the line number reported on the last line of each log message.