Writing Messages to a Log file

Hello,

I’d like to write a function that will print all logging statements to a file. I’ve tried the following based on the Logging documentation but nothing gets written to the file.

My naive first pass was to wrap my function call inside of a function that opens and closes the log file. The function f would be something like my_function_call(args...). The body of my_function_call is sprinkled with @debug, @warn, etc.

function with_logfile(f)
    io = open("logfile.txt", "w+")
    logger = SimpleLogger(io, Logging.Debug)
    with_logger(logger) do
        f
    end
    flush(io)
    close(io)
end

I have also tried the following but the result is the same, logfile.txt is empty.

function with_logfile(f)
    io = open("logfile.txt", "w+")
    logger = SimpleLogger(io, Logging.Debug)
    global_logger(logger)
    f;
    close(io)
end

The only way it writes to the file is if I explicitly write the logging statements like this


function with_logfile(f)
    io = open("logfile.txt", "w+")
    logger = SimpleLogger(io, Logging.Debug)
    global_logger(logger)
    @debug "This gets written to a file"
    f # but nothing from here does
    close(io)
end

Note, I can see the debug statements in the REPL when I run with_logfile().

I would appreciate any hints. Sorry if this is something obvious. I have never used logging.

You’re never calling f in your function (should be f()).

1 Like

Hm - I agree that seems like that should be the problem except when I did f() I then got an error about tuples not being callable. Somehow I think the result of f was getting produced sooner than I understood/expected? There must be something wrong with how I am using f in this context.

I did end up fixing this though. Not sure it is a good or long-term fix. But instead of having a separate function I added a keyword arg to f that creates a log file, something like as follows.

function f(args...;with_logfile=false)
    if with_logfile
        io = open("logfile.txt", "w+")
        logger = SimpleLogger(io, Logging.Debug)
        global_logger(logger)
    end
    # Other function calls here, to actual computations, hot inner loops, etc.
    if with_logfile
        close(io)
    end
    # Return result of f
    return a, b
end