title: How to shutdown the logger in python after a function containing it is interrupted?
body: <p>I am using the <a href="https://docs.python.org/3/library/logging.html" rel="nofollow noreferrer">logging module</a> in python inside a function. A simplified structure of the code is like below.</p>
  <pre><code>def testfunc(df):
      import logging
      import sys
      from datetime import datetime
      logger = logging.getLogger()
      logger.setLevel(logging.INFO)
      # to print to the screen
      ch = logging.StreamHandler(sys.__stdout__)
      ch.setLevel(logging.INFO) 
      logger.addHandler(ch)
      #to print to file
      fh = logging.FileHandler('./data/treatment/Treatment_log_'+str(datetime.today().strftime('%Y-%m-%d'))+'.log')
      fh.setLevel(logging.INFO) 
      logger.addHandler(fh)
      #several lines of code and some information like:
      logger.info('Loop starting...')
  
      for i in range(6):   # actually a long for-loop 
          #several lines of somewhat slow code (even with multiprocessing) and some information like:
          logger.info('test '+str(i))
              
      logging.shutdown()    
  
      return None
  </code></pre>
  <p>So, I know:</p>
  <ul>
  <li>the logger need to be shutdown (<code>logging.shutdown()</code>);</li>
  <li>and it is included at the end of the function.</li>
  </ul>
  <p>The issue is:</p>
  <ul>
  <li>the actual function deals with subsets of a data frame, and sometimes it results in error because no sufficient data, etc.</li>
  <li>If I run the function again, what I see is all messages are repeated twice (or even more, if I need to run again).</li>
  <li>The situation remind the reported <a href="https://stackoverflow.com/q/6729268/8939181">here</a>, <a href="https://stackoverflow.com/q/58238598/8939181">here</a>, and <a href="https://stackoverflow.com/a/4566411/8939181">here</a>, for example... But slightly different...</li>
  </ul>
  <p>I got, it is because the <code>logging</code> module was not shutdown, neither the handlers were removed... And I understand for the final function, I should anticipate such situations, and include steps to avoid raising errors, like shutdown the logger and finish  the function, etc... But currently I am even using the log information to identify such situations...</p>
  <p>My question is: how can I shut down it once such situation (function aborted because error) happened? ... in my current situation, in which I am just testing the code? Currently, the way to make it stop is to start the new console in Spyder (in my understanding, restarting the kernel). What is the correct procedure in this situation?</p>
  <p>I appreciate any help...</p>
  <hr />