Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get logger to delete existing log file before writing to it again?

Using the configuration below, my logfile will be called 'test-debug.log' and it will grow infinitely for everytime I run the script. I just want this logfile to contain the log records from the most recent run of the script. The log should be deleted before starting again.

How do I do that?

logger = logging.getLogger('test') #Create a log with the same name as the script that created it logger.setLevel('DEBUG')   #Create handlers and set their logging level filehandler_dbg = logging.FileHandler(logger.name + '-debug.log') filehandler_dbg.setLevel('DEBUG')    #Create custom formats of the logrecord fit for both the logfile and the console streamformatter = logging.Formatter(fmt='%(levelname)s:\t%(threadName)s:\t%(funcName)s:\t\t%(message)s', datefmt='%H:%M:%S') #We only want to see certain parts of the message   #Apply formatters to handlers filehandler_dbg.setFormatter(streamformatter)   #Add handlers to logger logger.addHandler(filehandler_dbg) 
like image 874
Paul H Avatar asked Feb 06 '14 00:02

Paul H


People also ask

How do you clear a python logger?

You'd have to signal to the daemon that the log file's been removed so it can close/reopen the log file handle and start using the new log file. Otherwise it'll just keep writing to the old one, which will still exist somewhere until all filehandles on it are closed. Give mode="w" to logging. FileHandler .


1 Answers

Try this:

filehandler_dbg = logging.FileHandler(    logger.name + '-debug.log',     mode='w') 

to open the filename in write mode instead of append mode, clobbering logger.name

More information: logging.FileHandler docs, open() and list of modes

like image 50
dmcc Avatar answered Sep 22 '22 21:09

dmcc