Programing

파이썬 예외를 기록하는 방법?

lottogame 2020. 11. 16. 07:44
반응형

파이썬 예외를 기록하는 방법?


이 질문에 이미 답변이 있습니다.

Python에서 예외를 어떻게 기록 할 수 있습니까?

몇 가지 옵션을 살펴본 결과이 코드를 사용하여 실제 예외 세부 정보에 액세스 할 수 있음을 알았습니다.

import sys
import traceback

try:
    1/0
except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_traceback)

어떻게 든 print_exception()stdout에 문자열을 던져서 기록하고 싶습니다.


Python 3.5에서는 exc_info 인수에 예외 인스턴스를 전달할 수 있습니다.

import logging
try:
    1/0
except Exception as e:
   logging.error('Error at %s', 'division', exc_info=e)

살펴보기 logging.exception( Python Logging Module )

import logging 
def foo():
    try:
        some_code()
    except:
        logging.exception('')

이것은 현재 예외에 대한 트레이스 백을 자동으로 가져와 적절하게 로깅합니다.


질문에 답하기 위해 함수 print_exception()사용하는 문자열 버전을 얻을 수 있습니다 traceback.format_exception(). 트레이스 백 메시지를 stdout에 인쇄하지 않고 문자열 목록으로 반환하므로 원하는 작업을 수행 할 수 있습니다. 예를 들면 :

import sys
import traceback

try:
    asdf
except NameError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
    print ''.join('!! ' + line for line in lines)  # Log it or whatever here

다음이 표시됩니다.

!! Traceback (most recent call last):
!!   File "<stdin>", line 2, in <module>
!! NameError: name 'asdf' is not defined

그러나 rlotun이 제안한대로 표준 Python 로깅 모듈을 사용하는 것이 좋습니다. 설정하기 가장 쉬운 것은 아니지만 매우 사용자 정의 할 수 있습니다.


예외 로깅은 로그 메시지에 exc_info = True 키워드 인수를 추가하는 것만 큼 간단 합니다. http://docs.python.org/2/library/logging.html의 Logger.debug 항목을 참조하십시오 .

예:

try: 
    raise Exception('lala')
except Exception:
    logging.info('blah', exc_info=True)

출력 (물론 로그 처리기 구성에 따라 다름) :

2012-11-29 10:18:12,778 - root - INFO - <ipython-input-27-5af852892344> : 3 - blah
Traceback (most recent call last):
  File "<ipython-input-27-5af852892344>", line 1, in <module>
    try: raise Exception('lala')
Exception: lala

우선 except 절에 적절한 Exception 유형을 사용하는 것을 고려하십시오. 그런 다음 예외 이름을 지정하여 인쇄 할 수 있습니다.

try:
    1/0
except Exception as e:
    print e

Dependending on your Python version, you must use

except Exception, e

참고URL : https://stackoverflow.com/questions/4508849/how-to-log-python-exception

반응형