python does not release filehandles to logfile

后端 未结 3 395
误落风尘
误落风尘 2020-11-28 10:02

I have an application which has to run a number of simulation runs. I want to setup a logging mechanisme where all logrecords are logged in a general.log, and all logs for a

相关标签:
3条回答
  • 2020-11-28 10:17

    You need to call .close() on the filehandler.

    When your Run class completes, call:

    handlers = self.log.handlers[:]
    for handler in handlers:
        handler.close()
        self.log.removeHandler(handler)
    
    0 讨论(0)
  • 2020-11-28 10:18

    You can also shutdown the logging completely. In that case, file handles are being released:

    logging.shutdown()
    

    It will close opened handles of all configured logging handlers.

    I needed it to be able to delete a log file after a unit test is finished and I was able to delete it right after the call to the logging.shutdown() method.

    0 讨论(0)
  • 2020-11-28 10:27

    I was using an interactive Python environment (Spyder). Apparently, Spyder uses logging internally. So, logging.shutdown() does not produce the desired effect. The next execution of the same program doubled log records, the 3rd execution tripled them, etc. Handlers are apparently not removed by shutdown() in this environment. Also, I did not disrupt Spyder in any way by issuing an explicit shutdown() call. Puzzling.

    Martijn's code to explicitly close and remove the handlers, one at a time, did work in the Spyder environment.

    0 讨论(0)
提交回复
热议问题