1

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')
Tonechas
  • 13,398
  • 16
  • 46
  • 80

2 Answers2

0

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.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
0

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()
Flair
  • 2,609
  • 1
  • 29
  • 41