Logging to a file and closing it again properly (logging module)

C

Christoph Haas

Evening,

I have an application that is running in an endless loop processing an
incoming queue. Every run is supposed to write a log file about the run
and then close it again. While the 'logging' module is generally working
well (even though the documentation makes me miss some proper examples
how everything works together) I can't seem to close the log file again
to open a new one.

This is basically what I'm doing:

log = logging.getLogger("myapplication")
log.addHandler(logging.FileHandler("/tmp/testfile"))
log.setLevel(logging.INFO)
log.info("foo")

Now I'm missing a way to tell this handler to go away. Through 'ipython'
I found out there is a log.handlers array that contains all the
handlers. Perhaps I could delete all of them but I'm sure there is a
more proper way to close files again.

Googling found me:

.>>> logging._handlers.clear()
.>>> logging.root.handlers = []
.>>> for l in logging.Logger.manager.loggerDict.values():
.>>> l.handlers = []

But this looks really really ugly. I don't like to mess with the gears
in the 'logging' module.

Ideas?

Kindly
Christoph
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top