2017-04-19 3 views
0

모든 예외를 catch하고 다음 코드를 사용하여 로그 파일에 기록하려고합니다. 그러나 어떤 이유로 인해이를 catch하지 못합니다. 코드는 다음과 같습니다Jupyter Python의 예외 포수가 작동하지 않습니다. (sys.excepthook)

다음
# Prepares logging 
import logging 
import time 
output_folder='whatever' 
# Logging to file: 
today=time.strftime("%Y%M%d %H:%M:%S") 
logging.basicConfig(filename=output_folder+'/logger '+today+'.log',level=logging.DEBUG, 
        format='%(asctime)s %(message)s', filemode='w') 
logging.info('Program started.') 

# Every time there is an error, catch it 
import sys 
#def error_catching(exctype, value, tb): 
def log_uncaught_exceptions(ex_cls, ex, tb): 
    print "Error found" 
    logging.critical(''.join(traceback.format_tb(tb))) 
    logging.critical('{0}: {1}'.format(ex_cls, ex)) 

sys.excepthook = log_uncaught_exceptions 

내가 존재하지 않는 변수 ('m')를 호출하여, 예를 들어, 오류를 생성하고 난 오류가 발생하지만, 아무것도 로그 파일에 로그입니다 :

m #this should generate a NameError, which is the following 

--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
<ipython-input-9-69b64623f86d> in <module>() 
----> 1 m 

NameError: name 'm' is not defined 

로그 파일은 아무 것도 포착하지 않습니다. 나는 무엇을 잘못 했는가?

감사합니다.

+0

iPython이이 훅에 의존하는지 잘 모르겠습니다. 나는 그 자체로 후크가 있다고 생각한다. 앞으로 24 시간 내에 아무 것도 제공되지 않으면 더 나은 대답을하려고 노력할 것입니다. – Josay

+0

http://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook (아마도 중복 질문 ...) – Josay

+0

Josay, 의견에 감사드립니다. 중복 된 것으로 표시된 답변에는 몇 가지 공통점이 있지만 해당 질문에서 선택한 대답은 정답이 아니며 가능성이 있습니다. 너의 방법을 시도하고 너에게 돌아올거야. – Escachator

답변

1

면책 조항 : 공개 된 바운티가있는 질문은 분명히 닫힐 수 없습니다. 따라서, 내 답변은 대부분 this other similar question/answer을 기반으로합니다.

변경 sys.excepthook은 iPython에서 작동하지 않습니다.

해결 방법은 IPython.core.interactiveshell.InteractiveShell.showtraceback입니다.

danrobinson/tracestack과 같은 일부 프로젝트에서는 추가 설명과 이에 대한 수정 사항을 확인할 수 있습니다.

+0

이것은 굉장히 좋습니다. 고마워요 ~ 조세이 – Escachator