Skip to content

Commit

Permalink
Allow AnnotatedStrings in log messages (JuliaLang#51802)
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 Mar 4, 2024
1 parent 692069b commit 7116067
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 inference,
# and reduce the risk of resulting method invalidations.
message = string(message)
msglines = if Base._isannotated(message) && !isempty(Base.annotations(message))
message = Base.AnnotatedString(String(message), Base.annotations(message))
@NamedTuple{indent::Int, msg::Union{SubString{Base.AnnotatedString{String}}, SubString{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 7116067

Please sign in to comment.