hand made class with destructor and the logging module

Vinay Sajip vinay_sajip at yahoo.co.uk
Thu Oct 28 00:41:43 CEST 2010


On Oct 27, 3:21 pm, climb65 <clim... at free.fr> wrote:
> This class has a destructor which is expected to log something into my log
> file if a crash occurs.
> Well, the destructor works well but during the crash, python has already
> closed the log file and the reference to the Logger has been set to None.
> So, I can't log anything!
>
> How is it possible to solve this problem?
>

Unfortunately, when a process is about to exit (for whatever reason),
things may not shut down in an order you would like. I'd advise
wrapping your main program in an try: except: block. If you have a
main, function, for example:

import logging, sys

logger = logging.getLogger(__name__)

def main():
    #configure logging, say using basicConfig()
    try:
        # here is whatever your main program is doing now
        retcode = 0
    except Exception:
        logger.exception('Exception raised during processing')
        retcode = 1
    sys.exit(retcode)

if __name__ == '__main__':
    main()



More information about the Python-list mailing list