I want to setup a global logger and write the logging messages into a file. Here is what I did for this purpose.
module Example
using Logging
function setlogger()
io = open("/tmp/log.txt", "w+")
logger = SimpleLogger(io)
global_logger(logger)
return nothing
end
function closelogger()
close(global_logger().stream)
end
function test()
setlogger()
@info "Test message"
@info "Test message"
closelogger()
end
export setlogger, test, closelogger
end
and here is the console output when I tested logging
julia> using Example
julia> test()
[ Info: Test message
[ Info: Test message
The problem is that the logging messages are written into the console, not in the file /tmp/log.txt
which is empty.
Any ideas what I am doing wrong?
Your example works as expected for me:
julia> test()
shell> cat /tmp/log.txt
β Info: Test message
β @ Main.Example REPL[1]:18
β Info: Test message
β @ Main.Example REPL[1]:19
Yes, it worked when I launched julia from terminal, using Example
and calling test
. But I realized that it does not work when I launch julia repl in Juno. Seems interesting to me. May be a kind of bug in Juno I think.
Yeah, this is a Juno specific problem β weβre wrapping everything the user executes in a
with_logger(JunoProgressLogger(current_logger())) do
eval(usercode)
end
where the JunoProgressLogger
delegates all log messages to the former current_logger
. This means that the new global logger you set in your user code will never be used.
To solve that you could either set the global logger in an extra statement (which is obviously not a great solution) or just use with_logger
in your code as well, which imho should be the preferred over messing around with global_logger
anyways.
1 Like
Thank you for the reply. Yeah, with_logger
is what I should use, though it is not a global logger, to work in Juno.
Here is the last case.
module Example
using Logging
function setlogger()
io = open("/tmp/log.txt", "w+")
SimpleLogger(io)
end
function test()
logger = setlogger()
with_logger(logger) do
@info "Test message"
@info "Test message"
end
flush(logger.stream)
end
export setlogger, test
end