I want to ensure that my program runs without doing questionable operations. Thus I would like the program to terminate whenever a warning is thrown; i.e. promote a warning to the level of errors.
Is there a way to do this? I have the Python equivalent warnings.filterwarnings("error") of the warnings package in mind.
Julia doesn’t “throw” warnings. However, warning messages are typically written to the stderr stream, so you can turn such warnings to errors simply by redirecting stderr to a read-only stream:
julia> redirect_stderr(open(touch(tempname()), "r"))
IOStream(<file ...>)
julia> @warn "foo"
ERROR: ArgumentError: write failed, IOStream is not writeable
(With a bit more work, I guess you could change stderr to a pipeline of some sort that captures the warning message and re-prints it.)
If you just want to promote the level from warning to error you can do that with a custom logger too, but as Steven said, error log messages don’t terminate the process (@error "something" is not the same as error("something")):
julia> using LoggingExtras, Logging
julia> promoter = TransformerLogger(global_logger()) do log_args
if Logging.Error > log_args.level >= Logging.Warn
return merge(log_args, (; level = Logging.Error))
else
return log_args
end
end;
julia> global_logger(promoter);
julia> @info "hello"
[ Info: hello
julia> @warn "warn"
┌ Error: warn
└ @ Main REPL[11]:1
Like all errors it should render a stacktrace if uncaught.
But if you are just raising it to @error level you can put in the stacktrace in the transformer logger manually.
like is shown in: