Skip to content

Commit 1998518

Browse files
authored
Allow AnnotatedStrings in log messages (#51802)
Permitting annotated strings allows for styling information to be preserved through to log printing.
1 parent 93876c9 commit 1998518

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

stdlib/Logging/src/ConsoleLogger.jl

+11-2
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,17 @@ function handle_message(logger::ConsoleLogger, level::LogLevel, message, _module
118118
end
119119

120120
# Generate a text representation of the message and all key value pairs,
121-
# split into lines.
122-
msglines = [(indent=0, msg=l) for l in split(chomp(convert(String, string(message))::String), '\n')]
121+
# split into lines. This is specialised to improve type inference,
122+
# and reduce the risk of resulting method invalidations.
123+
message = string(message)
124+
msglines = if Base._isannotated(message) && !isempty(Base.annotations(message))
125+
message = Base.AnnotatedString(String(message), Base.annotations(message))
126+
@NamedTuple{indent::Int, msg::Union{SubString{Base.AnnotatedString{String}}, SubString{String}}}[
127+
(indent=0, msg=l) for l in split(chomp(message), '\n')]
128+
else
129+
[(indent=0, msg=l) for l in split(
130+
chomp(convert(String, message)::String), '\n')]
131+
end
123132
stream::IO = logger.stream
124133
if !(isopen(stream)::Bool)
125134
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
(:log_debug, "Debug:", "@ Base ~/somefile.jl:42")

0 commit comments

Comments
 (0)