7

I'm writing to log file using the following code:

import logging
from gmplot import gmplot
logging.basicConfig(filename="sample.log", level=logging.INFO)
logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")

But then it's impossible to delete this file. how can I 'release' this file?

asked May 7, 2018 at 13:17

2 Answers 2

7

You need to close() your logging:

As explained there: python does not release filehandles to logfile

When your Run class completes, call:

handlers = self.log.handlers[:]
for handler in handlers:
 handler.close()
 self.log.removeHandler(handler)
answered May 7, 2018 at 13:23
Sign up to request clarification or add additional context in comments.

2 Comments

What would be the handler in the example of the question that must be closed?
If handlers is empty replace the first self.log with logging.getLogger() instead of logging.getLogger(__name__).
4

simply use logging.shutdown(), when you are done with logging.

answered Jul 20, 2021 at 10:52

1 Comment

This is the solution for those here getting PermissionError

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.