Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close logger file?

Tags:

logging

ruby

I've just read the Logger gem documentation and the method close called my attention. Now I'm wondering if I have to close logger file after using it, like:

log = Logger.new("foo.log")
# program here logging things
log.close

I've never closed it before and it doesn't seem to be an issue, maybe it's closed automatically when the program finishes?

like image 653
Redithion Avatar asked Jan 02 '18 14:01

Redithion


People also ask

What is the purpose of a logger?

A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.

Why should logs be flushed before exiting a program?

For safety, flush often. This will mean that the run-time library will not try to buffer writes until it has lots of data -- you may crash before that's written!

What does logging StreamHandler do?

The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods). Returns a new instance of the StreamHandler class.


1 Answers

TL;DR: you should not unless you know for sure you should.

The Logger has a LogDevice that might be any device: a file, a port, a socket, a pipe. Some devices are known to be fine with a concurrent access, but most of them are not. E.g. if you have a socket as a logging device, any other attempt to write to this socket will be prevented by OS. Concurrent writing to files, though possible in general, is not advised, because you’ll end up having a messed chunks there.

Unless you expect some other application is going to access the same device for writing, you are safe not closing the device. It’ll be closed automatically when the Logger is GC’ed.

On the other hand, if you are writing to the shared file, or expect that the destination might be used by 3rd parties during your program is alive, it’s safer to close the device once it becomes unneeded to allow concurrent access to it for the other writers.

NB: Logger#close actually closes the underlying device:

# File logger.rb, line 569
def close
  @logdev.close if @logdev
end
like image 79
Aleksei Matiushkin Avatar answered Sep 16 '22 20:09

Aleksei Matiushkin