21
使用下面的配置,我的日志文件将被称为'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)
谢谢,现在的作品完美..我实际上看过'filehandler'的文档,但没有关于'mode = a'是什么和为什么是默认的更多信息。现在我想我明白它来自'fileIO'语法或类似的东西? –
没问题。这里列出了所有模式:http://docs.python.org/2/library/functions.html#open – dmcc
它是一个耻辱,记录的文档不会链接回该函数#打开页面,会非常有用。 –