2016-01-21 136 views
1

我不明白爲什麼日誌事件正在打印到控制檯,當我沒有定義控制檯處理程序。我讀過的所有示例都明確定義了一個控制檯處理程序(streamhandler),以便將消息輸出到控制檯。Python日誌記錄 - 防止日誌事件被打印到控制檯

我希望只將這些事件打印到文件中。

import logging 
logger = logging.getLogger(__name__) 

my_format = '%(asctime)-25s %(levelname)-8s LOGGER: %(name)-12s MODULE: %(module)-15s FUNCTION: %(funcName)-30s MSG: %(message)s' 
my_datefmt ='%m/%d/%Y %I:%M:%S%p' 
logging.basicConfig(format=my_format, datefmt=my_datefmt, level=logging.DEBUG) 
formatter = logging.Formatter(my_format, datefmt=my_datefmt) 
logger.setLevel(logging.DEBUG) 
handler1 = logging.FileHandler('mylog.txt') 
handler1.setLevel(logging.DEBUG) 
handler1.setFormatter(formatter) 
logger.addHandler(handler1) 

logger.debug("Why is this printed to the console") 

編輯:

有人指出,我並沒有考慮到根記錄。在調用logging.basicConfig時,默認的流處理程序被添加到根記錄器(logger = getLogger())

根記錄器的處理程序可以修改,但是我發現我可以防止我的記錄器傳播日誌到根記錄器。

這是可以做到像這樣:

import logging 
logger = logging.getLogger(__name__) 

my_format = '%(asctime)-25s %(levelname)-8s LOGGER: %(name)-12s MODULE: %(module)-15s FUNCTION: %(funcName)-30s MSG: %(message)s' 
my_datefmt ='%m/%d/%Y %I:%M:%S%p' 
logging.basicConfig(format=my_format, datefmt=my_datefmt, level=logging.DEBUG) 
formatter = logging.Formatter(my_format, datefmt=my_datefmt) 
logger.setLevel(logging.DEBUG) 
handler1 = logging.FileHandler('mylog.txt') 
handler1.setLevel(logging.DEBUG) 
handler1.setFormatter(formatter) 
logger.addHandler(handler1) 
logger.propagate = False    #### 
logger.debug("Why is this printed to the console") 

回答

2
> ipython 
import logging 
logging.basicConfig? 

*****************logging.basicConfig************** 
Signature: logging.basicConfig(**kwargs) 
Docstring: 
Do basic configuration for the logging system. 

This function does nothing if the root logger already has handlers 
configured. It is a convenience method intended for use by simple scripts 
to do one-shot configuration of the logging package. 

The default behaviour is to create a StreamHandler which writes to 
sys.stderr, set a formatter using the BASIC_FORMAT format string, and 
add the handler to the root logger. 
... 

你有2個處理器。

+0

感謝您的回答。 – Voldemort

+0

不客氣... errr他的名字不會說出來。 – Back2Basics

相關問題