Logging module doesn't replace properly my log file when I set mode = 'w' to FileHandler

482 Views Asked by At

I'm trying to overwrite the log file every time that I run my program, but instead, it overwrites the file with the outputs the same number of times as I've run the program. Does anyone know why is this happening?

If I run the code below once, it will save the string 'test 1' once and if I run it for the second time but with the string 'test 2', it overwrites the log file with 'test 2' twice and so on...

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(name)s \n %(message)s')
file_handler = logging.FileHandler('/data/logging_data_val.log', mode ='w')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.info('test')
2

There are 2 best solutions below

0
Vinay Sajip On

This will only happen if the above code is in a module that you import multiple times - not if you just put it in a foo.py file and run it using python foo.py. That's because every time you import it, you add a handler - so, multple handlers are adeded to the same logger - which leads to messages being repeated.

0
John Sandoval On

I figure it out!!, I'm no sure why but I need to clear the handler before running the program again. I only added this code in the second line and it worked fine.

if (logger.hasHandlers()):
    logger.handlers.clear()