title: Python Logging - closing filehandlers for multiple modules
body: <p>I'm trying to log info from multiple modules that I've created. I have a main script (<code>main.py</code>) and another module (let's call it <code>mymodule.py</code>). I've set up a logger in each module as follows:</p>
  
  <pre><code>logger = logging.getLogger(__name__)
  logger.setLevel(logging.DEBUG)
  
  # create a file handler
  file_handler = logging.FileHandler('debug.log', mode='a')
  file_handler.setLevel(logging.DEBUG)
  
  # create a logging format
  # we're limiting the levelname to 1 char: I=INFO, D=DEBUG and so on
  formatter = logging.Formatter('[%(levelname).1s][%(module)14s:%(funcName)-15s]-&gt; %(message)s')
  file_handler.setFormatter(formatter)
  
  # add the handler to the logger
  logger.addHandler(file_handler)
  </code></pre>
  
  <p>In main.py I load <code>mymodule.py</code> and I do the following at the end of all processing.</p>
  
  <pre><code>file_handler.close()
  logger.removeHandler(file_handler)
  </code></pre>
  
  <p>Now the problem is that once the script stops running I can't delete debug.log unless I close Spyder. Also, for each subsequent run I get duplicate entries from <code>mymodule.py</code> like this.</p>
  
  <pre><code>[D][mymodule:__init__       ]-&gt; object created
  [D][mymodule:__init__       ]-&gt; object created
  </code></pre>
  
  <p>So it appears that there is an open file handler that I've left hanging. How do I close it. If I have to add a <code>file_handler.close()</code> in <code>mymodule.py</code> where do I add it?</p>
  
  <p>EDIT: I tried this in <code>main.py</code></p>
  
  <pre><code># clean up file handlers
  handlers = logger.handlers[:]
  for handler in handlers:
      handler.close()
      logger.removeHandler(handler)
  </code></pre>