CiaranWelsh
CiaranWelsh

Reputation: 7681

Logging to python file doesn't overwrite file when using the mode='w' argument to FileHandler

I have some code to set up a log in Python 2.7 (using the logging module):

import os
import logging
logger=logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log')
handler=logging.FileHandler(log_filename,mode='w')
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.debug('debugging message')

This code works and I am getting the output, however I intend to use this log to do a lot of debugging so I want to overwrite the log file each time its run. In the docs say to use the mode keyword argument to the 'FileHandler. It doesn't specify precisely *which* mode to use for overwrite file each time but I think a reasonable assumption would bemode='w'`. This however doesn't work. Can anybody tell me why?

Upvotes: 19

Views: 20275

Answers (5)

michalxo
michalxo

Reputation: 101

This worked for me: (missing force=True) The actual answer is to add the filemode = 'w' AND force = True parameter to basicConfig. from https://stackoverflow.com/a/71259043/2604720

Upvotes: 0

Denis
Denis

Reputation: 781

Replace this line

logger.addHandler(handler)

By this one:

logger.handlers=[handler]

Upvotes: 0

NutCracker
NutCracker

Reputation: 12273

This solves problem for me:

handler = logging.FileHandler(log_filename, 'w+')

Upvotes: 25

CiaranWelsh
CiaranWelsh

Reputation: 7681

The problem is that the file doesn't actually get overwritten until a new python shell is started.

Upvotes: 9

AndrewG
AndrewG

Reputation: 79

I am not familiar with this to much, and I did not really see anything that stuck out in google. Have you tried just using:

    handler=logging.FileHandler(log_filename, 'w')

Upvotes: 5

Related Questions