2015-11-06 94 views
0

我用下面的語句創建日誌:Python記錄,不寫時間戳到輸出文件

module = sys.modules['__main__'].__file__ 
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, 
       format='%(asctime)s %(name)s (%(levelname)s): %(message)s') 
log = logging.getLogger(module) 

然後我有我的腳本選項編寫使用參數-o輸出到文件中。我認爲這是與發生本聲明一個問題,當一個人指定他們希望寫入磁盤日誌:

if arguments.o: 
    fh = RotatingFileHandler(arguments.o, mode='a', maxBytes=2*1024*1024, 
         backupCount=2, encoding=None, delay=0) 
    fh.setLevel(logging.DEBUG) 
    log.addHandler(fh) 

無需添加額外的日期時間聲明的文本字符串,是有辦法做到這一點使用格式參數?

2015-11-06 07:27:13,592 C:\GIS\move_content\src\updatecontent.py (INFO): Reading Configuration file 

這裏是什麼配置輸出:

Reading Configuration file 

謝謝

答案我發現:基於

這裏是上打印生產我的一個響應,我能夠將其添加到我的代碼,並且輸出現在看起來正確:

# create formatter and add it to the handlers 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
fh.setFormatter(formatter) 

回答

0

文件處理程序使用不同的格式字符串,您應該手動將它設置爲文件處理程序。

例子:

fh.setFormatter(formatter) 

Cookbook for Python 3 (Python 2 is the same for this question)

+0

@Penguinlog - 你可以提供設置的FileHandler記錄的例子嗎? –

+0

那麼設置setFormater()你不會傳入一個字符串? '%(asctime)s%(name)s(%(levelname)s):%(message)s' –

+0

以下是答案:#create formatter並將其添加到處理程序 formatter = logging.Formatter('% asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) –