Python logging close log

Robson Dantas Lab

This one was a bit hard to figure out. I´m doing some spiders and using logging.getLogger interface to make a good log file.

I´m calling on wrapper to generate a log file, and calling this wrapper twice, makes the logger generate duplicated lines.

Just to make the things a bit clear, take a look at this routine:

import logging import logging.handlers def makelog(filepath): logger = logging.getLogger('applog') # remove diretorio dir = os.path.split(filepath) dir = diretorio[0] # cria dir tree if not os.path.exists(dir): os.makedirs( dir ) # rotate 2mb de log, in 5 files hdl = logging.handlers.RotatingFileHandler( filepath, maxBytes=2097152, backupCount=5) formatter = logging.Formatter('%(asctime)s %(module)s, line %(lineno)d %(levelname)s %(message)s') hdl.setFormatter(formatter) logger.addHandler(hdl) logger.setLevel(logging.DEBUG) return logger

Now, make two different classes and call this function. Even though destroying the class and calling the other one, the records will be duplicated during your second call.

To make it work, it´s a bit complicated to find, and here is the solution:

Inside your __del__(self) function, include:

x = logging._handlers.copy() for i in x: log.removeHandler(i) i.flush() i.close()

PS: I´m supposing that “log” is your return for the function, your in other words, the result of logging.getLogger(..) .

I hope it saves some hours of your work 🙂

Источник

Читайте также:  PHP - Hello, World!
Оцените статью