From d4f2c3a5771f06d86e9d22ade12eedde3068fe6b Mon Sep 17 00:00:00 2001 From: TEC Date: Sat, 21 Oct 2023 10:32:19 +0800 Subject: [PATCH] Allow AnnotatedStrings in log messages Permitting annotated strings allows for styling information to be preserved through to log printing. --- stdlib/Logging/src/ConsoleLogger.jl | 12 ++++++++++-- stdlib/Logging/test/runtests.jl | 9 +++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/stdlib/Logging/src/ConsoleLogger.jl b/stdlib/Logging/src/ConsoleLogger.jl index 1d45296c907d17..1bf8534e8c0fe4 100644 --- a/stdlib/Logging/src/ConsoleLogger.jl +++ b/stdlib/Logging/src/ConsoleLogger.jl @@ -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 diff --git a/stdlib/Logging/test/runtests.jl b/stdlib/Logging/test/runtests.jl index e0fc6a0bc3770f..61a8c76d9de59f 100644 --- a/stdlib/Logging/test/runtests.jl +++ b/stdlib/Logging/test/runtests.jl @@ -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")