Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add try/catch around handle_message() to catch errors during logging. #57004

Merged
merged 5 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion base/logging/logging.jl
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ function logmsg_code(_module, file, line, level, message, exs...)
end
line = $(log_data._line)
local msg, kwargs
$(logrecord) && invokelatest($handle_message,
$(logrecord) && $handle_message_nothrow(
logger, level, msg, _module, group, id, file, line;
kwargs...)
end
Expand All @@ -420,6 +420,18 @@ function logmsg_code(_module, file, line, level, message, exs...)
end
end

@noinline function handle_message_nothrow(logger, level, msg, _module, group, id, file, line; kwargs...)
@nospecialize
try
@invokelatest handle_message(
logger, level, msg, _module, group, id, file, line;
kwargs...)

catch err
@invokelatest logging_error(logger, level, _module, group, id, file, line, err, true)
end
end

function process_logmsg_exs(_orig_module, _file, _line, level, message, exs...)
@nospecialize
local _group, _id
Expand Down
13 changes: 13 additions & 0 deletions test/corelogging.jl
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,19 @@ end
@test only(collect_test_logs(logmsg)[1]).kwargs[:x] === "the y"
end
end
@testset "Log message handle_message exception handling" begin
# Exceptions in log handling (printing) of msg are caught by default.
struct Foo end
Base.show(::IO, ::Foo) = 1 ÷ 0

# We cannot use `@test_logs` here, since test_logs does not actually _print_ the message
# (i.e. it does not invoke handle_message). To test exception handling during printing,
# we have to use `@test_warn` to see what was printed.
@test_warn r"Error: Exception while generating log record in module .*DivideError: integer division error"s @info Foo()

# Exceptions in log handling (printing) of attributes are caught by default
@test_warn r"Error: Exception while generating log record in module .*DivideError: integer division error"s @info "foo" x=Foo()
end

@testset "Special keywords" begin
logger = TestLogger()
Expand Down
Loading