2013-02-12 81 views
1

我正在運行一個web服務器龍捲風,我試圖使用以下命令將所有日誌輸出重定向到一個文件。但是我沒有看到文件中的輸出。Python重定向日誌

/usr/bin/python -u index.py 2>&1 >> /tmp/tornado.log 

我將-u選項傳遞給python解釋器。我仍然沒有看到任何輸出記錄到我的日誌文件中。

但是,我看到,當我這樣做stdout上輸出

/usr/bin/python index.py 
+0

將文件處理程序附加到應用程序工作中的根記錄器中? – 2013-02-12 07:54:01

回答

0

龍捲風使用內置的日誌模塊。您可以輕鬆地將文件處理程序附加到根記錄器,並將其級別設置爲NOTSET,以便記錄所有內容或其他級別(如果要過濾)。

參考文檔:logginglogging.handlers

例,與龍捲風的記錄工作:

import logging 
# the root logger is created upon the first import of the logging module 

# create a file handler to add to the root logger 
filehandler = logging.FileHandler(
    filename = 'test.log', 
    mode = 'a', 
    encoding = None, 
    delay = False 
) 

# set the file handler's level to your desired logging level, e.g. INFO 
filehandler.setLevel(logging.INFO) 

# create a formatter for the file handler 
formatter = logging.Formatter('%(asctime)s.%(msecs)d [%(name)s](%(process)d): %(levelname)s: %(message)s') 

# add filters if you want your handler to only handle events from specific loggers 
# e.g. "main.sub.classb" or something like that. I'll leave this commented out. 
# filehandler.addFilter(logging.Filter(name='root.child')) 

# set the root logger's level to be at most as high as your handler's 
if logging.root.level > filehandler.level: 
    logging.root.setLevel = filehandler.level 

# finally, add the handler to the root. after you do this, the root logger will write 
# records to file. 
logging.root.addHandler(filehandler) 

往往不是,我其實是想抑制龍捲風的記錄器(因爲我有我自己的,並吸引他們例外,並且它們最終會污染我的日誌),這就是在文件處理程序中添加篩選器非常方便的地方。

相關問題