This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: logging.shutdown() not correct for chained handlers
Type: Stage:
Components: Library (Lib) Versions: Python 2.4
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: vinay.sajip Nosy List: fdij, vinay.sajip
Priority: normal Keywords:

Created on 2005-09-05 21:12 by fdij, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg26215 - (view) Author: Fons Dijkstra (fdij) Date: 2005-09-05 21:12
Consider the following code:

import logging
import logging.handlers

if __name__ == "__main__":
    fh = logging.handlers.RotatingFileHandler("log.txt")
    mh = logging.handlers.MemoryHandler(1024, 
logging.ERROR, fh)
    logging.getLogger().addHandler(mh)
    logging.getLogger().warning("next statement crashes")
    logging.shutdown()

which results in a crash due to operating on a closed 
file. The reason is that the shutdown flushes and closes 
all handlers in undefined order. In above case, first 
the 'fh' handlers is flushes and closed then the 'mh' 
handler.

The solution is to first flush all handlers times the 
number of handlers before closing them. Thus (omitting 
error handling):

def shutdown():
    for i in range(len(_handlers)):
        for h in _handlers.keys():
            h.flush()
    for h in _handlers.keys():
        h.close()
msg26216 - (view) Author: Vinay Sajip (vinay.sajip) * (Python committer) Date: 2005-09-07 11:12
Logged In: YES 
user_id=308438

There is indeed a problem - thanks for the report. Rather
than your proposed solution, I would rather add another
internal list, _handlerList, which holds the handlers in
*reverse* order of creation. When shutting down, (a copy of)
this list is used for the iteration rather than
_handlers.keys().

I may remove _handlers in the future - I can't remember why
I made it a dict rather than a list.

Will check into CVS soon, then mark this as Fixed.
msg26217 - (view) Author: Vinay Sajip (vinay.sajip) * (Python committer) Date: 2005-09-19 01:01
Logged In: YES 
user_id=308438

Now checked into CVS.
History
Date User Action Args
2022-04-11 14:56:12adminsetgithub: 42344
2005-09-05 21:12:16fdijcreate