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

Amit Khemka khemkaamit at gmail.com
Wed Jun 14 02:59:22 EDT 2006


On 6/13/06, Christoph Haas <email at christoph-haas.de> wrote:
> 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 = []

You can "close" the logger by just removing the handler from the logging object

# first creater a logger and file handler
fooLogger = logging.getLogger('FOO')
fooLogger.setLevel(logging.INFO)
fl = logging.FileHandler('foo.txt)
fl.setLevel(logging.INFO)
fooLogger.addHandler(fl)

# remove the handler once you are done
fooLogger.removeHandler(fl)

cheers,
amit.
-- 
----
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.



More information about the Python-list mailing list