0

I am testing the logger's functionality and it requires me to create a log file, but at the end I want to remove it so I tried to os.remove in the tearDownClass

@classmethod
def tearDownClass(cls) -> None:
    log = logging.getLogger('client_logger')

    try:
        log.removeHandler(log.handlers.pop())
    except:
        pass
    os.remove('client_logger.log')

I read that the RotatingFileHandler is the cause of it and once I remove it the handler list is empty, but it still gives me PermissionError: [WinError 32].

RnD
  • 1,019
  • 5
  • 23
  • 49
  • 1
    My best guess is that it's still not closed by the logger for some reason. Is there anyway that you can double check that the file isn't being used by the module? – Andrew McGrail Aug 12 '19 at 13:48
  • @AndrewMcGrail not sure how to do that so I am open to suggestions – RnD Aug 12 '19 at 13:50
  • I tried to rename it and it's the same exception, so it's being used by the program for sure, the question is how to forcefully close it – RnD Aug 12 '19 at 13:52
  • Check the [close](https://docs.python.org/2/library/logging.html) method maybe? I think that would work? Or maybe the ```shutdown``` method. – Andrew McGrail Aug 12 '19 at 14:18

1 Answers1

0

Log files work like any other ordinary files. It must be opened and closed. The same goes for the log files. The log handlers opens a file to write into. This means it before the file can be removed it should be disconnected to the log handler.

Example with Django TestCase:


import os
import logging
from django.test import TestCase


_logger = logging.getLogger("logger_name")

class CustomTestCase(TestCase):

    def setUp(self) -> None:
        ... # stuff

    def test_more_stuff(self) -> None:
        ... # more stuff

    def tearDown(self) -> None:
        # First close logger file before removing.

        _logger.handlers[0].close() # <FileHandler D:\path\to\logfile\test.log (DEBUG)>

        if os.path.exists("test.log"):
            os.remove("test.log")


The following StackOverflow page helped me find a solution.

Reference: python does not release filehandles to logfile