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()
和模式列表