[Python] Python logging MemoryHandler leaks memory?

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    In a main.py file I have following code:

    import time

    from v1 import log, ServiceLogger
    from logging.handlers import MemoryHandler


    class Service:
    h = MemoryHandler(1000)
    id = None
    log = None

    def __init__(self, id: int):
    self.id = id
    self.log = ServiceLogger(log)
    log.addHandler(self.h)

    def do(self):
    print("Do some job per service!")


    def service_exec():
    service = Service(id=4)
    service.do()


    if __name__ == '__main__':
    while True:
    for i in range(10):
    service_exec()
    time.sleep(1)


    And then v1.py has following content:

    import logging

    log = logging.getLogger('.'.join(__name__.split('.')[:-1]))


    class ServiceLogger(logging.LoggerAdapter):
    def log(self, level, msg, *args, **kwargs):
    print("Custom logger hello!")


    The problem is that over a time (~15-30 mins) I noticed that my computer memory increases over a period, and continue to grow forever with around 15-30 mins intervals. I used top -p <PID> to track the "VIRT RES SHR" resources, in particular that "RES". However, if I remove this log.addHandler(self.h) code snippet, then memory doesn't grow (so I left computer for couple hours and no grow has been noticed). Could somebody hint me what kind of problem could this be and how to solve it?

    Continue reading...

Compartilhe esta Página