2013-06-21 49 views
1

如何在不知道記錄器名稱的情況下使班級的記錄沉默?有問題的類是qualysconnectPython:特定班級記錄器的setLevel

import logging 
import qualysconnect.util 

# Set log options. This is my attempt to silence it. 
logger_qc = logging.getLogger('qualysconnect') 
logger_qc.setLevel(logging.ERROR) 
# Define a Handler which writes WARNING messages or higher to the sys.stderr 
logger_console = logging.StreamHandler() 
logger_console.setLevel(logging.ERROR) 
# Set a format which is simpler for console use. 
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') 
# Tell the handler to use this format. 
logger_console.setFormatter(formatter) 
# Add the handler to the root logger 
logging.getLogger('').addHandler(logger_console) 

# 'application' code 
logging.debug('debug message') 
logging.info('info message') 
logging.warn('warn message') 
logging.error('error message') 
logging.critical('critical message') 

輸出時import qualysconnect.util被註釋掉:

root  : ERROR error message 
root  : CRITICAL critical message 

輸出時import qualysconnect.util保持在:

WARNING:root:warn message 
ERROR:root:error message 
root  : ERROR error message 
CRITICAL:root:critical message 
root  : CRITICAL critical message 

回答

0

可悲的是,他們並沒有爲他們的記錄器定義的名稱,如在qualysconnect.util他們甚至不做一個getLogger電話或getChild電話,你不能做一個不會影響整體的事情e模塊的記錄行爲不會變髒。

唯一干淨的選擇,我能想到的是報告他們處理記錄爲錯誤的方式,請在您修改qualysconnect.util記錄語句像補丁請求:

import logging 
logger = logging.getLogger('qualysconnect').getChild('util') 

,並更換所有logging.info()logging.debug() ...到logger.info()logger.debug() ...

骯髒的選項:您可以猴修補qualysconnect.util模塊,使您有一個記錄器對象替換其logging對象:

import qualysconnect.util 
logger_qc = logging.getLogger('qualysconnect') 
logger_qc.setLevel(logging.ERROR) 
qualysconnect.util.logging = logger_qc.getLogger('qualysconnect').getChild('util') 
qualysconnect.util.logging.disable(logging.CRITICAL) # will disable all logging for CRITICAL and below 

這可能是您向上遊項目發送補丁請求時的工作解決方案,但肯定不是一個長期的工作解決方案。

或者你可以簡單地關閉整個qualysconnect模塊的所有註銷,但我不認爲這就是你想要的。

+1

我是來源的貢獻者,我懷疑這是解決方案:https://bitbucket.org/uWaterloo_IST_ISS/python-qualysconnect/issue/19/set-logger-name – paragbaxi

+0

非常感謝您的確認! – paragbaxi

+0

創建我自己的班級qualysapi。嘗試實現包級別日誌記錄。有什麼建議? – paragbaxi