title: How can I prevent the inheritance of python loggers and handlers during multiprocessing based on fork?
body: <p>Suppose I configured logging handlers in the main process. The main process spawns some children and due to <code>os.fork()</code> (in Linux) all loggers and handlers are inherited from the main process. In the example below <code>'Hello World'</code> would be printed 100 times to the console:</p>
  
  <pre><code>import multiprocessing as mp
  import logging
  
  
  def do_log(no):
      # root logger logs Hello World to stderr (StreamHandler)
      # BUT I DON'T WANT THAT!
      logging.getLogger().info('Hello world {}'.format(no))
  
  
  def main():
      format = '%(processName)-10s %(name)s %(levelname)-8s %(message)s'
  
      # This creates a StreamHandler
      logging.basicConfig(format=format, level=logging.INFO)
  
      n_cores = 4
      pool = mp.Pool(n_cores)
      # Log to stdout 100 times concurrently
      pool.map(do_log, range(100))
      pool.close()
      pool.join()
  
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p>This will print something like:</p>
  
  <pre><code>ForkPoolWorker-1 root INFO     Hello world 0
  ForkPoolWorker-3 root INFO     Hello world 14
  ForkPoolWorker-3 root INFO     Hello world 15
  ForkPoolWorker-3 root INFO     Hello world 16
  ...
  </code></pre>
  
  <p>However, I don't want the child process to inherit all the logging configuration from the parent. So in the example above <code>do_log</code> should not print anything to <code>stderr</code> because there should be no <code>StreamHandler</code>.</p>
  
  <p>How do I prevent inheriting the loggers and handlers without removing or deleting them in the original parent process?</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> Would it be a good idea to simply remove all handlers at the initialization of the pool?</p>
  
  <pre><code>def init_logging():
      for logger in logging.Logger.manager.loggerDict.values():
          if hasattr(logger, 'handlers'):
              logger.handlers = []
  </code></pre>
  
  <p>and</p>
  
  <pre><code>pool = mp.Pool(n_cores, initializer=init_logging, initargs=())
  </code></pre>
  
  <p>Moreover, can I also safely <code>close()</code> all (file) handlers during the initialization function?</p>