Skip to content

Commit

Permalink
Allow AnnotatedStrings in log messages
Browse files Browse the repository at this point in the history
Permitting annotated strings allows for styling information to be
preserved through to log printing.
  • Loading branch information
tecosaur committed Feb 11, 2024
1 parent af90dac commit c766cbf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
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 inferesence,
# and reduce the risk of resulting method invalidations.
message = string(message)
msglines = if Base._isannotated(message)
message = Base.AnnotatedString(String(message), Base.annotations(message))
@NamedTuple{indent::Int, msg::SubString{<:Union{Base.AnnotatedString{String}, 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')]
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

0 comments on commit c766cbf

Please sign in to comment.