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
它是一個恥辱,記錄的文檔不會鏈接回該函數#打開頁面,會非常有用。 –