LoginSignup
0
0

More than 1 year has passed since last update.

例外処理で大元のエラー箇所をlogしたい時

Posted at

結論

some.py
import sys
import traceback
from some_module import some_func

def some_some():
    try:
        some_process...
        some_val = some_func()  # エラーが起こる処理 -> さらに some_func()で呼んでいるsome_blah_func()でraiseしてるとする
    except Exception as e:
        t, v, tb = sys.exc_info()
        print(traceback.format_tb(tb)[-1])  # <-大元のエラー箇所を出力する

すると出力はこんな感じ。

some_container     |   File "/some_path/some_blah_module.py", line 30, in some_blah_func
some_container     |   raise

解説

sys.exc_info()の中にはこんな感じに例外オブジェクトの情報がある

type, value, tb = sys.exc_info()
print(type)
print(value)
print(tb)

some_container     | <class 'RuntimeError'>
some_container     | No active exception to reraise
some_container     | <traceback object at xxxxxxxx>

なので、traceback.format_tbに、ここで取得したtracebackを食わせると…

print(traceback.format_tb(tb))
some_container     | ['  File "/some_path/some.py", line 10, in some_some\n    some_val = some_func()\n', '  File "/some_path/some_moduile.py", line 20, in some_func\n    some_val2 = some_blah_func()\n', '  File "/some_path/some_blah_module.py", line 30, in some_blah_func\n    raise\n']

こんな感じ。
要するに、traceback.format_tb(tb)には、遡って各エラー箇所がリストで入っている。
なので、以下で大元をprintできる。

t, v, tb = sys.exc_info()
print(traceback.format_tb(tb)[-1]) 

あとは、これをloggingすればよし。

おわり。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0