Logging with custom messages

Hello Julia community,

I read the logging documentation, but I am still struggling to create a custom logger. Basically, what I want to do is to replicate what I do in python, that is, to create a logger on info level, but to show the function name, line number, time that the line was executed, and the message. In python, it would be something like:

fmt_file = (
    "%(levelname)s %(asctime)s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s"
)
file_formatter = logging.Formatter(fmt_file, "%Y-%m-%d %H:%M:%S")

In Julia, I tried:

@logmsg Logging.Info "Message" _line=__LINE__

but it does not print the line.

Can you let me know how I can make this to work, or what other approach I can use?

Thanks in advance for any help or insight that you can provide.

How about this?

using Logging, LoggingExtras, Dates

logger = FormatLogger(stderr) do io, args
    print(io, args.level, " ")
    Dates.format(io, now(), dateformat"yyyy-mm-dd HH:MM:SS")
    print(io, " [", args.file, ":", args.line, "] ")
    println(io, args.message)
end

global_logger(logger)

@debug "hello debug message"
@info "hello info message"
@warn "hello warning message"
@error "hello error message"

with output

$ julia run.jl 
Debug 2021-06-10 22:27:58 [/tmp/run.jl:12] hello debug message
Info 2021-06-10 22:27:58 [/tmp/run.jl:13] hello info message
Warn 2021-06-10 22:27:58 [/tmp/run.jl:14] hello warning message
Error 2021-06-10 22:27:58 [/tmp/run.jl:15] hello error message
3 Likes

Fredrik, thank you so much! this is exactly what I was looking for :clap: