I’m trying to implement something like Python’s decorators so that I can log whenever a function get’s called (eventually I want to log execution time / exceptions / etc)
This is the API I’d like to have:
@log_calls function foo(a, b,c) ... end
foo is called, it will log “calling foo” and “called foo” when it’s done.
I though that would be a good use of a macro, and this is something I found and modified a bit:
macro log_calls(func) name = func.args.args hiddenname = gensym() func.args.args = hiddenname _decorator(f) = (args...) -> begin @info "calling $(name)" f(args...) @info "called $(name)" end quote $func $(esc(name)) = $_decorator($hiddenname) end end
This works when used from the same module it get’s called, but I’d like to put it in some
Utils module, but then it breaks because it seems it tries to define
func in the scope of the
Utils module so I get undefined variables errors.
Is it possible to do that in Julia?
What am I missing?