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')
This will only happen if the above code is in a module that you
importmultiple times - not if you just put it in afoo.pyfile and run it usingpython 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.