Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

logging

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?

like image 532
CiaranWelsh Avatar asked Jul 16 '16 08:07

CiaranWelsh


People also ask

How do you overwrite a log in Python?

The filemode can be changed to write mode, which will overwrite the previous logs and only save the current ones. Since the filemode is set to w , this means that the log file will be opened in write mode each time basicConfig() is run, which will ultimately overwrite the file.

What is FileHandler in logging?

FileHandler. The FileHandler class, located in the core logging package, sends logging output to a disk file. It inherits the output functionality from StreamHandler . Returns a new instance of the FileHandler class.

Does Python open overwrite?

Example 1: Using the open() method to overwrite a file. It will delete the existing content from a file first; then, we can write new content and save it.


Video Answer


2 Answers

This solves problem for me:

handler = logging.FileHandler(log_filename, 'w+')
like image 159
NutCracker Avatar answered Oct 20 '22 01:10

NutCracker


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

like image 8
CiaranWelsh Avatar answered Oct 20 '22 02:10

CiaranWelsh