[英]Imported module adding unwanted logging. How can it be suppressed?
在導入我需要使用的模塊后,我看到了額外的日志消息。 我正在努力找出阻止這種情況發生的正確方法。 以下代碼最佳顯示問題:
import os
import logging
import flickrapi
class someObject:
def __init__(self):
self.value = 1
logger = logging.getLogger(__name__)
print logger.handlers
logger.info("value = " + str(self.value))
def main():
# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)-15s] %(name)-8s %(levelname)-6s %message)s')
fh = logging.FileHandler(os.path.splitext(os.path.basename(__file__))[0]+".log")
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.debug("Debug message")
logger.info("Info message")
thingy = someObject()
if __name__ == "__main__":
main()
使用flickrapi導入,我看到以下輸出:
DEBUG:__main__:Debug message
[2013-05-03 12:10:47,755] __main__ INFO Info message
INFO:__main__:Info message
[<logging.FileHandler instance at 0x1676dd0>, <logging.StreamHandler instance at 0x1676ea8>]
[2013-05-03 12:10:47,755] __main__ INFO value = 1
INFO:__main__:value = 1
刪除flickrapi導入后,我看到正確的輸出:
[2013-05-03 12:10:47,755] __main__ INFO Info message
[<logging.FileHandler instance at 0x1676dd0>, <logging.StreamHandler instance at 0x1676ea8>]
[2013-05-03 12:10:47,755] __main__ INFO value = 1
這是我第一次使用日志記錄,這讓我有點難過。 我已經閱讀了幾次文檔,但我認為我在理解中遺漏了一些東西。
查看logging.Logger.manager.loggerDict
,還有其他記錄器,但每個.handlers
都是空的。 __main__
記錄器只有我添加的兩個處理程序,所以這些消息來自哪里?
關於如何解決這個問題的任何指示都會非常感激,因為我已經碰壁了。
謝謝
這是您正在使用的flickrapi庫中的錯誤。 它在__init__.py
調用logging.basicConfig() , 這對於庫來說是錯誤的,因為它將一個StreamHandler默認添加到stderr到根記錄器。
您應該與作者一起打開錯誤報告。 python日志文檔中有一個關於庫應如何配置日志記錄的HOWTO 。
要解決此問題,直到修復錯誤,您應該能夠執行以下操作:
# at the top of your module before doing anything else
import flickrapi
import logging
try:
logging.root.handlers.pop()
except IndexError:
# once the bug is fixed in the library the handlers list will be empty - so we need to catch this error
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.