Python 如何让记录器在再次写入之前删除现有的日志文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21591748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:13:41  来源:igfitidea点击:

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

pythonloggingfilehandler

提问by Paul H

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.

使用下面的配置,我的日志文件将被称为“test-debug.log”,并且每次运行脚本时它都会无限增长。我只希望这个日志文件包含最近运行脚本的日志记录。在重新开始之前应该删除日志。

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)

采纳答案by dmcc

Try this:

尝试这个:

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

to open the filename in writemode instead of appendmode, clobbering logger.name

write模式而不是append模式打开文件名,破坏logger.name

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

更多信息:logging.FileHandler文档open()和模式列表

回答by Sumit Kumar

If you are using any external configuration file then pass 'w' for write mode in args of the handler.

如果您使用任何外部配置文件,则在处理程序的 args 中为写入模式传递“w”。

[loggers]
keys=root

[logger_root]
level=DEBUG
handlers=file_handler

[handlers]
keys=file_handler

[handler_file_handler]
class=FileHandler
formatter=formatter
args=("../log/test" + time.strftime("%%Y%%m%%d%%H%%M%%S") + '.log', 'w')

[formatters]
keys=formatter

[formatter_formatter]
format=%(asctime)s %(levelname)-5s [%(module)s] %(message)s