program story

아무것도 출력하지 않는 Python 로깅

inputbox 2020. 11. 28. 09:16
반응형

아무것도 출력하지 않는 Python 로깅


내가 쓰는 파이썬 스크립트에서 로깅 모듈을 사용하여 이벤트를 기록하려고합니다. 로거를 구성하려면 다음 코드가 있습니다.

ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s"
DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s"
LOG_CONFIG = {'version':1,
              'formatters':{'error':{'format':ERROR_FORMAT},
                            'debug':{'format':DEBUG_FORMAT}},
              'handlers':{'console':{'class':'logging.StreamHandler',
                                     'formatter':'debug',
                                     'level':logging.DEBUG},
                          'file':{'class':'logging.FileHandler',
                                  'filename':'/usr/local/logs/DatabaseUpdate.log',
                                  'formatter':'error',
                                  'level':logging.ERROR}},
              'root':{'handlers':('console', 'file')}}
logging.config.dictConfig(LOG_CONFIG)

를 실행하려고 할 때 문서의이 페이지에 루트 로거가 메시지를 출력해야 한다고 말 logging.debug("Some string")하더라도 콘솔에 출력이 표시되지 않습니다. 내 프로그램이 아무 것도 출력하지 않는 이유는 무엇이며 어떻게 수정할 수 있습니까?logging.debug


기본 로깅 수준은 경고입니다. 레벨을 변경하지 않았으므로 루트 로거의 레벨은 여전히 ​​경고입니다. 즉, 디버그 로깅을 포함하여 경고보다 낮은 수준의 로깅은 무시됩니다.

이것은 튜토리얼에 설명되어 있습니다 .

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

레벨이 정보보다 높기 때문에 'info'라인은 아무것도 인쇄하지 않습니다.

레벨을 변경하려면 루트 로거에서 설정하십시오.

'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

즉, level = DEBUG로 핸들러를 정의하는 것으로는 충분하지 않습니다. 실제 로깅 레벨도 DEBUG가되어야 출력 할 수 있습니다.


수년이 지난 후에도 여전히 Python 로거에 사용성 문제가있는 것 같습니다. 다음은 예제와 함께 몇 가지 설명입니다.

import logging
# This sets the root logger to write to stdout (your console)
logging.basicConfig()

# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)

# The following line sets the root logger level as well:
logging.basicConfig(level=logging.NOTSET)


# You can either share the `logger` object between all your files or the
# handle `my-app`. The result is the same.
logger = logging.getLogger("my-app")

logger.info("this will get printed")

# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")

# If you wish to control the logging levels, you can set the level anywhere in the
# hierarchy:
#
# - root
#   - my-app
#     - component-a
#

# Example for development:
logger.setLevel(logging.DEBUG)

# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)


# For production you rather want:
logger.setLevel(logging.WARNING)

일반적인 혼동의 원인은 잘못 초기화 된 루트 로거에서 비롯됩니다. 이걸 고려하세요:

import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")

산출:

woot
WARNING:myapp:woot

런타임 환경 및 로깅 수준에 따라 첫 번째 로그 줄이 어디에도 표시되지 않을 수 있습니다.


시도해 볼까요? 제 경우에는 모든 핸들러를 제거한 후 문제가 해결 된 것 같습니다.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)

여기에 아주 간단한 대답을 원하는 사람이라면 표시 할 수준을 설정하기 만하면됩니다. 내 모든 스크립트의 맨 위에 방금 넣었습니다.

import logging
logging.basicConfig(level = logging.INFO)

그런 다음 해당 수준 이상을 표시하려면 :

logging.info("Hi you just set your fleeb to level plumbus")

It is a hierarchical set of levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

The levels are DEBUG, INFO, WARNING, and ERROR. Default setting is WARNING.

This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

참고URL : https://stackoverflow.com/questions/7016056/python-logging-not-outputting-anything

반응형