我有一些代碼建立日誌在Python 2.7:記錄到蟒文件不使用模式時,「W」的參數(使用記錄模塊)改寫文件=到的FileHandler
import os
import logging
logger=logging.getLogger('CopasiTools')
logger.setLevel(logging.DEBUG)
log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log')
handler=logging.FileHandler(log_filename,mode='w')
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.debug('debugging message')
這代碼的作品和我得到的輸出,但我打算,所以我想每次都覆蓋日誌文件,它的運行使用此日誌中做了很多的調試。在docs說使用mode
關鍵字參數以「的FileHandler . It doesn't specify precisely *which* mode to use for overwrite file each time but I think a reasonable assumption would be
模式=」 w'`。但是這不起作用。有人可以告訴我爲什麼嗎?
我無法重現行爲。我使用了您提供的代碼,只是更改了文件名,每次運行代碼時都會覆蓋日誌。如果我將'mode'改爲'a',那麼新的運行會將行添加到末尾, – niemmi
這很奇怪,可能與以前的[question]有關(http://stackoverflow.com/questions/38396050/why-does-this -code換創建-A-python的日誌 - 不工作?noredirect = 1個#comment64203174_38396050)我有。你知道是否有可能永久覆蓋日誌記錄模塊的基本行爲? – CiaranWelsh
我不知道這樣做的方式,但這並不意味着這是不可能的, – niemmi