Skip to content

Commit d4f2c3a

Browse files
committed
Allow AnnotatedStrings in log messages
Permitting annotated strings allows for styling information to be preserved through to log printing.
1 parent 3d8b107 commit d4f2c3a

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

stdlib/Logging/src/ConsoleLogger.jl

+10-2
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,16 @@ function handle_message(logger::ConsoleLogger, level::LogLevel, message, _module
116116
end
117117

118118
# Generate a text representation of the message and all key value pairs,
119-
# split into lines.
120-
msglines = [(indent=0, msg=l) for l in split(chomp(convert(String, string(message))::String), '\n')]
119+
# split into lines. This is specialised to improve type inferesence,
120+
# and reduce the risk of resulting method invalidations.
121+
msglines = if message isa Base.AnnotatedString
122+
message = Base.AnnotatedString(String(message), Base.annotations(message))
123+
@NamedTuple{indent::Int, msg::SubString{<:Union{Base.AnnotatedString{String}, String}}}[
124+
(indent=0, msg=l) for l in split(chomp(message), '\n')]
125+
else
126+
[(indent=0, msg=l) for l in split(
127+
chomp(convert(String, string(message))::String), '\n')]
128+
end
121129
stream::IO = logger.stream
122130
if !(isopen(stream)::Bool)
123131
stream = stderr

stdlib/Logging/test/runtests.jl

+9
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ end
5252
end
5353
@test String(take!(buf)) == ""
5454

55+
# Check that the AnnotatedString path works too
56+
with_logger(logger) do
57+
@info Base.AnnotatedString("test")
58+
end
59+
@test String(take!(buf)) ==
60+
"""
61+
[ Info: test
62+
"""
63+
5564
@testset "Default metadata formatting" begin
5665
@test Logging.default_metafmt(Logging.Debug, Base, :g, :i, expanduser("~/somefile.jl"), 42) ==
5766
(:blue, "Debug:", "@ Base ~/somefile.jl:42")

0 commit comments

Comments
 (0)