プログラムを停止せずに完全なトレースバックを出力するには?
エラーでプログラムを停止したくない場合は、そのエラーを try/except で処理する必要があります。
try:
do_something_that_might_error()
except Exception as error:
handle_the_error(error)
完全なトレースバックを抽出するにはtraceback
、標準ライブラリのモジュールを使用します。
import traceback
そして、かなり複雑なスタックトレースを作成して、完全なスタックトレースを取得できることを示します。
def raise_error():
raise RuntimeError('something bad happened!')
def do_something_that_might_error():
raise_error()
印刷
完全なトレースバックを出力するには、次のメソッドを使用しますtraceback.print_exc
。
try:
do_something_that_might_error()
except Exception as error:
traceback.print_exc()
どちらが印刷されますか:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
印刷、ログ記録よりも優れています:
ただし、ベスト プラクティスは、モジュールにロガーを設定することです。モジュールの名前を認識し、レベルを変更できます (ハンドラーなどの他の属性の中で)。
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
その場合、logger.exception
代わりに関数が必要になります。
try:
do_something_that_might_error()
except Exception as error:
logger.exception(error)
どのログ:
ERROR:__main__:something bad happened!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
または、単に文字列が必要な場合は、traceback.format_exc
代わりに関数が必要になります。
try:
do_something_that_might_error()
except Exception as error:
logger.debug(traceback.format_exc())
どのログ:
DEBUG:__main__:Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
結論
3 つのオプションすべてについて、エラーが発生した場合と同じ出力が得られることがわかります。
>>> do_something_that_might_error()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
どちらを使用するか
通常は IO が支配的であるため、ここではパフォーマンスの問題は重要ではありません。前方互換性のある方法で要求されていることを正確に実行するため、私は好むでしょう:
logger.exception(error)
ロギング レベルと出力を調整できるため、コードに触れることなく簡単にオフにすることができます。通常、直接必要なことを実行することが最も効率的な方法です。