문제 설명
로깅 모듈 이상, 로그 메시지의 잘못된 표시? (Logging module weirdness, wrong display of log message?)
다음은 logging
모듈에 대해 내가 매우 이상하다고 생각하는 부분의 작은 예입니다.
import logging
logging.basicConfig()
#
# making a hierarchy like this:
# root
# |‑ session
# |‑session.foo
#
root_logger = logging.getLogger()
session_logger = logging.getLogger("session")
foo_logger = logging.getLogger("session.foo")
#
# root_logger and session_logger effective log levels
# are set to 30 (= WARNING)
#
foo_logger.debug("WA") #nothing is printed, so far so good
#
# and now enters the problem...
#
foo_logger.setLevel(logging.DEBUG)
foo_logger.debug("HELLO") #HELLO log message is printed!!!
'HELLO' 로그 메시지가 내 컴퓨터에 인쇄되는 이유를 모르겠습니다. 로거 foo_logger
에 첨부된 처리기가 없기 때문에 로그 메시지가 버블링되어야 하고 해당 수준이 <로 설정되어 있기 때문에 상위 수준 로거(session
)에 의해 효과적으로 중지되어야 합니다. code>WARNING (기본값).
foo_logger
에 레벨을 설정하면 핸들러를 통해 표시할 수 있는 권한이 부여되는 것처럼 보이지만 나에게는 매우 불분명합니다.
누가 메시지가 인쇄된 이유를 설명할 수 있습니까? 로거 계층 구조를 원하는 대로 만들려면 어떻게 해야 합니까?
참조 솔루션
방법 1:
Both loggers AND handlers have a level
setting, and the default level for handlers is 0
. You'd need to set the level of the parent handler ‑ in your case root_logger.handlers[0]
above logging.DEBUG
to filter out the debug()
calls on foo_logger
:
root_logger.handlers[0].level = logging.WARN
foo_logger.debug("peekaboo") # should not be printed
Note that logging.basicConfig()
only does a very simplistic config ‑ it's mostly meant as a way to get started with logging, for any serious configuration you want dictConfig
instead, which let you specify the handlers, formatters, levels etc as you see fit. Also note that a logger actually has a list of handlers (not a single one) and that multiple loggers can use the same handler, so who logs what (and where) depends on the combination of loggers AND handlers levels (and on the logger's propagate
option too).
As a practical example, on my current (django) project we have (amongst others) a "console" handler (logs to stdout, which gunicorn redirects to it's own log file) whose level is set to INFO and a "notify" handler (sends emails notifications) with level set to WARN, so that some of our loggers (those for the most sensitive parts) will send INFO and above messages to gunicorn's logs and send WARN messages and above as notification emails too.
(by mguijarr、bruno desthuilliers)