Creating a custom log message categorie

Sorry I couldn’t get back to you yesterday. This is what I had in mind:

julia> @logmsg Trace "This is the way it should be done"
[ Trace: This is the way it should be done

For the macro, I didn’t think I’d need so many things from CoreLogging for it to work:

using Logging

const Trace = LogLevel(500)

const _min_enabled_level = Base.CoreLogging._min_enabled_level
const current_logger_for_env = Base.CoreLogging.current_logger_for_env
const shouldlog = Base.CoreLogging.shouldlog
const handle_message = Base.CoreLogging.handle_message
const logging_error = Base.CoreLogging.logging_error

macro trace(exs...) Base.CoreLogging.logmsg_code((Base.CoreLogging.@_sourceinfo)..., :Trace, exs...) end

function Base.show(io::IO, level::LogLevel)
    if     level == Logging.BelowMinLevel  print(io, "BelowMinLevel")
    elseif level == Logging.Debug          print(io, "Debug")
    elseif level == Logging.Info           print(io, "Info")
    elseif level == Logging.Warn           print(io, "Warn")
    elseif level == Logging.Error          print(io, "Error")
    elseif level == Logging.AboveMaxLevel  print(io, "AboveMaxLevel")
    elseif level == Trace                  print(io, "Trace")
    else                           print(io, "LogLevel($(level.level))")
    end
end

Do note that this is type piracy and only works once since you’re overwriting Base.show, so it’s not really suited for a package or something like that. Also, since CoreLogging is technically not exported and internal, this might change at any time and shouldn’t be relied upon.

Here be dragons.

1 Like