在再次写入之前,如何让logger删除现有的日志文件?

Pau*_*l H 39 python logging filehandler

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

我怎么做?

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)
Run Code Online (Sandbox Code Playgroud)

dmc*_*mcc 47

试试这个:

filehandler_dbg = logging.FileHandler(logger.name + '-debug.log', mode='w')
Run Code Online (Sandbox Code Playgroud)

write模式而不是append模式打开文件名,clobberinglogger.name

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

  • 如果您使用“logging.basicConfig”,添加“filemode='w'”具有相同的效果。 (3认同)
  • 究竟.这里列出了所有模式:http://docs.python.org/2/library/functions.html#open (2认同)