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

Allow AnnotatedStrings in log messages #51802

Merged
merged 1 commit into from
Feb 17, 2024
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
13 changes: 11 additions & 2 deletions stdlib/Logging/src/ConsoleLogger.jl
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,17 @@ function handle_message(logger::ConsoleLogger, level::LogLevel, message, _module
end

# Generate a text representation of the message and all key value pairs,
# split into lines.
msglines = [(indent=0, msg=l) for l in split(chomp(convert(String, string(message))::String), '\n')]
# split into lines. This is specialised to improve type inference,
# and reduce the risk of resulting method invalidations.
message = string(message)
msglines = if Base._isannotated(message) && !isempty(Base.annotations(message))
message = Base.AnnotatedString(String(message), Base.annotations(message))
@NamedTuple{indent::Int, msg::Union{SubString{Base.AnnotatedString{String}}, SubString{String}}}[
(indent=0, msg=l) for l in split(chomp(message), '\n')]
else
[(indent=0, msg=l) for l in split(
chomp(convert(String, message)::String), '\n')]
vtjnash marked this conversation as resolved.
Show resolved Hide resolved
end
stream::IO = logger.stream
if !(isopen(stream)::Bool)
stream = stderr
Expand Down
9 changes: 9 additions & 0 deletions stdlib/Logging/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ end
end
@test String(take!(buf)) == ""

# Check that the AnnotatedString path works too
with_logger(logger) do
@info Base.AnnotatedString("test")
end
@test String(take!(buf)) ==
"""
[ Info: test
"""

@testset "Default metadata formatting" begin
@test Logging.default_metafmt(Logging.Debug, Base, :g, :i, expanduser("~/somefile.jl"), 42) ==
(:log_debug, "Debug:", "@ Base ~/somefile.jl:42")
Expand Down