title: Logging module: too many open file descriptors
body: <p>I am using Python <code>logging</code> module to print logs to a file, but I encountered the issue that "too many open file descriptors", I did remember to close the log file handlers, but the issue was still there.</p>
  
  <p>Below is my code</p>
  
  <pre><code>class LogService(object):
      __instance = None
      def __init__(self):
          self.__logger = logging.getLogger('ddd')
          self.__handler = logging.FileHandler('/var/log/ddd/ddd.log')
          self.__formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
          self.__handler.setFormatter(self.__formatter)
          #self.__logger.addHandler(self.__handler)
  
      @classmethod
      def getInstance(cls):
          if cls.__instance == None:
              cls.__instance = LogService()
  
          return cls.__instance
  
      # log Error
      def logError(self, msg):
          self.__logger.addHandler(self.__handler)
          self.__logger.setLevel(logging.ERROR)
          self.__logger.error(msg)
          # Remember to close the file handler
          self.closeHandler()
  
      # log Warning
      def logWarning(self, msg):
          self.__logger.addHandler(self.__handler)
          self.__logger.setLevel(logging.WARNING)
          self.__logger.warn(msg)
          # Remember to close the file handler
          self.closeHandler()
  
      # log Info
      def logInfo(self, msg):
          self.__logger.addHandler(self.__handler)
          self.__logger.setLevel(logging.INFO)
          self.__logger.info(msg)
          # Remember to close the file handler
          self.closeHandler()
  
      def closeHandler(self):
          self.__logger.removeHandler(self.__handler)
          self.__handler.close()
  </code></pre>
  
  <p>And after running this code for a while, the following showed that there were too many open file descriptors.</p>
  
  <pre><code>[root@my-centos ~]# lsof | grep ddd | wc -l
  11555
  </code></pre>