[英]Unexpected behavior of the Python logging module with info and warning messages
我有一個關於 Python 中的日志記錄模塊的問題。 如果我實例化一個記錄器並將其級別設置為 INFO 而不添加任何處理程序,那么我希望信息消息將打印在屏幕上。 但是,實際上,會打印警告消息,但不會打印信息消息。 顯式添加處理程序后,將打印兩個級別。
確切地說,以下小腳本:
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("This is an info message")
logger.warning("This is a warning message")
print("*** Add a stream handler explicitly")
handler = logging.StreamHandler()
logger.addHandler(handler)
logger.info("This is an info message")
logger.warning("This is a warning message")
給出 output
This is a warning message
*** Add a stream handler explicitly
This is an info message
This is a warning message
(在 Python 3.7.6 和 3.8.2 中檢查)。
我希望在沒有處理程序的情況下不打印任何消息,或者在將級別設置為 INFO 后打印兩個級別。
我建議你使用loguru 。 這是一個非常簡單易用的工具,對我來說非常直觀。
您可以僅使用此行添加默認記錄器:
from loguru import logger
如果要更改日志記錄級別,只需像這樣設置記錄器:
logger.remove() # This disables the default logger
logger.add(sys.stderr, level="INFO") # This adds a default logger (format and colors included) but at the logging level you need
就是這樣。 在您的代碼中使用 loguru 記錄器的所有腳本都將像這樣設置。 默認情況下,它輸出到 stderr,但您可以根據需要更改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.