[Python] Python proper logging with filehandlers

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am using python logging in my django application. A class that connects to a backend api initialises this logger with a filehandler if needed. The class gets instantiated everytime an api call is made. I have tried making sure additional handlers are not added every time, but

    lsof | grep my.log


    shows an increasing amount of handlers on my log file and after a while my server fails due to this open file limit.

    self.logger = logging.getLogger("FPA")

    try:
    if self.logger.handlers[0].__class__.__name__=="FileHandler":
    pass
    except Exception, e:
    print 'new filehandler added'+str(e)
    ch = logging.FileHandler(FPA_LOG_TARGET)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s - %(pathname)s @ line %(lineno)d")
    ch.setFormatter(formatter)
    self.logger.setLevel(logging.DEBUG)
    self.logger.addHandler(ch)


    I realise this may not be the best way to do this, but I have not found the error in my implementation so far.

    Continue reading...

Compartilhe esta Página