문제 설명
선언하기 전에 logging.info()를 호출하면 Python의 logging.basicConfig가 작동하지 않습니다. (logging.basicConfig in Python won't work if calling logging.info() before declaring)
이 답변을 기반으로 상세 로깅을 활성화하는 더 쉬운 방법
이 Python 스크립트를 사용하겠습니다.
import argparse
import logging
def main():
import argparse
import logging
parser = argparse.ArgumentParser(
description='A test script for http://stackoverflow.com/q/14097061/78845'
)
parser.add_argument("‑v", "‑‑verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
logging.info('Shown in debug and info mode')
logging.debug('Only shown in debug mode')
if __name__ == "__main__":
logging.info('Starting script!')
main()
터미널에서 이 스크립트를 python ‑m verbose ‑v
로 실행하면 아무 것도 인쇄되지 않습니다.
if __name__ == "__main__":
#logging.info('Starting script!')
main()
에서와 같이 파일에서 logging.info('Starting script!')
줄을 주석 처리하면 예상대로 로깅이 작동합니다.
그것 basicConfig
가 정의되기 전에 logging.info()
를 호출하려는 시도는 모든 로깅을 완전히 비활성화하는 것 같습니다.
로깅또는 일반적인 문제이며 왜 이런 일이 발생합니까?
저는 Python 3.6.7을 사용 중입니다.
참조 솔루션
방법 1:
From the logging
documentation: (Emphasis mine)
logging.basicConfig(**kwargs)
Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.
The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.
This function does nothing if the root logger already has handlers configured for it.
So basically your first call to logging.info
made some automatic configuration. Your later configuration attempt silently failed because of the automatic configuration that already happend.
방법 2:
Don't use basicConfig to change the level. Use logging.getLogger().setLevel(logging.DEBUG)
to change the level on the root logger. One can do this on any logger or handler as well.
(by Alex Tereshenkov、dgw、Dan D.)