Combination of FormatLogger and FileLogger in LoggingExtras

Is it possible to combine the capabilities of a FormatLogger and of a FileLogger in LoggingExtras.jl?

Quite obviously, the first one helps formatting logging messages with the other sends them to appropriate files. Though I can’t figure how to use both capabilities at the same time.

Here is an example of a logger using the package documentation

function init_logger()
   # fmt_logger = FormatLogger() do io,args
   #    println(io,args._module," | ","[",args.level,"] ",args.message)
   # end
   logger = TeeLogger(
        global_logger(),
        MinLevelLogger(FileLogger("info.log"), Logging.Info),
        MinLevelLogger(FileLogger("warn.log"), Logging.Warn),
        MinLevelLogger(FileLogger("error.log"), Logging.Error),
   )
   return logger
end

logger = init_logger()
with_logger(logger) do
       @info "blablabla"
       @warn "bliblibli"
       @error "blobloblo"
end

All that FileLogger really does is to open the file and pass it to a SimpleLogger. So to use a “FileLogger” for FormatLogger you can just open the files yourself and pass the IO: FormatLogger(fmt, open("info.log", "w")). Here is the full example:

function init_logger()
   function fmt(io, args)
       println(io, args._module, " | ", "[", args.level, "] ", args.message)
   end
   logger = TeeLogger(
        global_logger(),
        MinLevelLogger(FormatLogger(fmt, open("info.log", "w")), Logging.Info),
        MinLevelLogger(FormatLogger(fmt, open("warn.log", "w")), Logging.Warn),
        MinLevelLogger(FormatLogger(fmt, open("error.log", "w")), Logging.Error),
   )
   return logger
end

logger = init_logger()
with_logger(logger) do
       @info "blablabla"
       @warn "bliblibli"
       @error "blobloblo"
end
1 Like

Works like a charm, thanks !