I have a custom logger class that worked fine in one module, but if I use it in other module of the same package and with the same filehandler it multiplies record from 1 to n times. I use it in 5 threads that's why I'm trying to close filehandler each time message was recorded


class RootLogger():

    def __init__(self):
        self.logger = None

    # skeleton for creating custom logger
    # name - name of the logger, string or class/module name
    def set_config(self, name, logfile):
        self.logger = logging.getLogger(name)
        # format of the message
        formatter = logging.Formatter('%(asctime)s - [%(name)s] [%(levelname)s] %(message)s')
        # log file rotation, time
        handler = RotatingFileHandler(filename=logfile,
                                      maxBytes=8000000,
                                    backupCount=5,
                                    encoding='utf-8')
        #handler = StreamHandler()
        handler.setFormatter(formatter)
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(handler)
        self.logger.setLevel(logging.DEBUG)
        return self.logger

    # patch for excluding 'too many opened files' error
    def __del__(self):
        if self.logger:
            for hdlr in self.logger.handlers:
                #hdlr.flush()
                hdlr.close()
    # override commands
    def info(self, msg):
        self.logger.info(msg)
        self.__del__()
    def debug(self, msg):
        self.logger.debug(msg)
        self.__del__()
    def error(self, msg):
        self.logger.error(msg)
        self.__del__()
    def warning(self, msg):
        self.logger.warning(msg)
        self.__del__()
    def critical(self, msg):
        self.logger.warning(msg)
        self.__del__()

1 Answers

1
Devesh Kumar Singh On Best Solutions

You want to check if handlers already exist for the logger before creating more handlers.

self.logger = logging.getLogger(name)
if not self.logger.handlers:
    #Create the handlers