로깅 모듈 이상, 로그 메시지의 잘못된 표시? (Logging module weirdness, wrong display of log message?)


문제 설명

로깅 모듈 이상, 로그 메시지의 잘못된 표시? (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 mguijarrbruno desthuilliers)

참조 문서

  1. Logging module weirdness, wrong display of log message? (CC BY‑SA 2.5/3.0/4.0)

#Python #python-logging






관련 질문

Python - 파일 이름에 특수 문자가 있는 파일의 이름을 바꿀 수 없습니다. (Python - Unable to rename a file with special characters in the file name)

구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)

기본 숫자를 10 ^ 9 이상으로 늘리면 코드가 작동하지 않습니다. (Code fails to work when i increase the base numbers to anything over 10 ^ 9)

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Enthought Canopy의 Python: csv 파일 조작 (Python in Enthought Canopy: manipulating csv files)

학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)

다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)

여러 함수의 변수를 다른 함수로 사용 (Use variables from multiple functions into another function)

리프 텐서의 값을 업데이트하는 적절한 방법은 무엇입니까(예: 경사하강법 업데이트 단계 중) (What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent))

Boto3: 조직 단위의 AMI에 시작 권한을 추가하려고 하면 ParamValidationError가 발생합니다. (Boto3: trying to add launch permission to AMI for an organizational unit raises ParamValidationError)







코멘트