로깅 모듈을 사용하여 모든 잡히지 않은 예외를 기록하는 Python 프로그램을 설계하려고합니다. sys.excepthook 함수를 사용하여 기본 예외 처리를 재정의하면됩니다. 명령 줄에서 직접 프로그램을 실행하면 제대로 작동하지만 파일을 가져 오려고하면 작동하지 않는다는 것을 알았습니다. sys.excepthook 함수가 로깅 모듈을 인식하지 못하는 것 같습니다. 내가 명령 행 (./loggingTest.py
)에서이 작업을 실행하면sys.excepthook이 가져온 모듈에서 작동하지 않습니다
#! /usr/bin/env python2.7
import logging, sys
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler("test.log"))
print "outside of exception handler: logger = %s" % logger
def handleException(excType, excValue, traceback):
#global logger # this function doesn't work whether or not I include this line
print "inside exception handler: logger = %s" % logger
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
sys.excepthook = handleException
logger.debug("starting")
asdf # create an exception
, 그것은 잘 작동 예를 들면 다음과 같습니다. 예외가 기록, 나는이 출력 표시됩니다 : 나는 파이썬 인터프리터를 실행하고 파일 (import loggingTest
)을 가져 오려고 할 경우, 그러나
outside of exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
inside exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
를, 그것은 이상하게 역할을합니다. 예외는 기록되지 않고, 나는이를 참조하십시오
outside of exception handler: logger = <logging.RootLogger object at 0x7f8ab04f3ad0>
inside exception handler: logger = None
Error in sys.excepthook:
Traceback (most recent call last):
File "loggingTest.py", line 13, in handleException
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
AttributeError: 'NoneType' object has no attribute 'error'
Original exception was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "loggingTest.py", line 18, in <module>
asdf # create an exception
NameError: name 'asdf' is not defined
나는 어쩌면 sys.excepthook 이내에 다시 로깅 모듈을 가져 와서이 문제를 해결할 수 있습니다,하지만 난 여전히 궁금 : 왜 이런 일이?
그렇게하면 잘 작동합니다. sys.excepthook을 정의한 동일한 파일에서 예외를 생성하면 작동하지 않습니다. –
@ mikez302 : 죄송합니다. 답변을 변경했지만 어떤 방식 으로든 작동합니다. –
수정 한 후에도 스크립트를 직접 실행하면 스크립트가 제대로 작동하지만 가져 오면 스크립트가 작동하지 않습니다. –