Logging in Julia

Here’s the translation of the Go logging example to Julia, formatted in Markdown suitable for Hugo:

Julia provides several ways to handle logging, including the built-in Logging module and third-party packages. This example will demonstrate logging using the standard Logging module.

using Logging
using Dates

function main()
    # The default logger is already configured for reasonable logging
    # output to stderr. You can use @info, @warn, @debug, and @error macros.
    @info "standard logger"

    # You can set the minimum level of logging messages to display
    global_logger(ConsoleLogger(stderr, Logging.Info))
    @info "with microsecond precision" _time=now()

    # Julia doesn't have a built-in way to show file and line numbers,
    # but you can include them manually if needed
    @info "with file/line" _file=@__FILE__ _line=@__LINE__

    # You can create a custom logger with a specific stream and minimum level
    mylogger = ConsoleLogger(stdout, Logging.Info)
    with_logger(mylogger) do
        @info "from mylogger"
    end

    # You can add prefixes to log messages using string interpolation
    prefix = "ohmy:"
    @info "$(prefix) from mylogger"

    # To log to a buffer, you can use an IOBuffer
    buf = IOBuffer()
    buflogger = ConsoleLogger(buf, Logging.Info)
    with_logger(buflogger) do
        @info "hello"
    end

    # This will actually show it on standard output
    print("from buflogger:", String(take!(buf)))

    # Julia doesn't have a built-in structured logging solution like Go's slog,
    # but you can achieve similar results by passing key-value pairs
    @info "hi there" key="val" age=25
end

main()

To run the program, save it as logging.jl and use the julia command:

$ julia logging.jl

Sample output (the date and time emitted will depend on when the example ran):

┌ Info: standard logger
└ @ Main ~/logging.jl:6
┌ Info: with microsecond precision
│   _time = 2023-08-22T10:45:16.904141
└ @ Main ~/logging.jl:10
┌ Info: with file/line
│   _file = "/home/user/logging.jl"
│   _line = 14
└ @ Main ~/logging.jl:14
┌ Info: from mylogger
└ @ Main ~/logging.jl:20
┌ Info: ohmy: from mylogger
└ @ Main ~/logging.jl:24
from buflogger:┌ Info: hello
└ @ Main ~/logging.jl:31
┌ Info: hi there
│   key = "val"
│   age = 25
└ @ Main ~/logging.jl:37

This example demonstrates various logging techniques in Julia:

  1. Using the standard logger with different log levels.
  2. Setting the global logging level.
  3. Including additional information like timestamps and file/line numbers.
  4. Creating custom loggers for specific outputs.
  5. Logging to a buffer.
  6. Adding structured data to log messages.

While Julia’s logging system is different from Go’s, it provides similar functionality for most common logging needs. The Logging module is flexible and can be extended with third-party packages for more advanced use cases.