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 6, 2024
1 parent 3d8b107 commit d4f2c3a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 10 additions & 2 deletions stdlib/Logging/src/ConsoleLogger.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,16 @@ 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.
msglines = if message isa Base.AnnotatedString
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, 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) ==
(:blue, "Debug:", "@ Base ~/somefile.jl:42")
Expand Down

0 comments on commit d4f2c3a

Please sign in to comment.