2011-03-27 6 views
3

로깅 모듈을 사용하여 모든 잡히지 않은 예외를 기록하는 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 이내에 다시 로깅 모듈을 가져 와서이 문제를 해결할 수 있습니다,하지만 난 여전히 궁금 : 왜 이런 일이?

답변

3

이 문제는 Python bug tracker에 버그로보고되었습니다. 지금까지 누군가 Python 2.7과 2.7.1 사이에 확실히 변화가 있다고 응답했으며, 이것이 예상 된 동작이라고 생각합니다. 그는 모든 예외를 기록하기 위해 다음과 같이 제안했습니다.

def handleException(excType, excValue, traceback, logger=logger): 
    logger.error("Uncaught exception", exc_info=(excType, excValue, traceback)) 

sys.excepthook = handleException 
1

exhook.py에서 일어난 경우에도 오류를 재현 할 수 없습니다. 이 exhook.py입니다 : 다음

#! /usr/bin/env python2.7 
import logging, sys, traceback as tb 

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 
    tb.print_exception(excType, excValue, traceback) 
    print "inside exception handler: logger = %s" % logger 
    logger.error("Uncaught exception", exc_info=(excType, excValue, traceback)) 

sys.excepthook = handleException 

raise Exception 

:

Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win 
32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import exhook 
outside of exception handler: logger = <logging.RootLogger object at 0x02AB0A70> 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "exhook.py", line 18, in <module> 
    raise Exception 
Exception inside exception handler: logger = <logging.RootLogger object at 0x02AB0A70> 

그냥 잘 작동합니다. 이 방법이 효과가 있습니까?

+0

그렇게하면 잘 작동합니다. sys.excepthook을 정의한 동일한 파일에서 예외를 생성하면 작동하지 않습니다. –

+0

@ mikez302 : 죄송합니다. 답변을 변경했지만 어떤 방식 으로든 작동합니다. –

+0

수정 한 후에도 스크립트를 직접 실행하면 스크립트가 제대로 작동하지만 가져 오면 스크립트가 작동하지 않습니다. –

관련 문제