Pythonでstacktraceのログ出力

traceback.format_exc呼べばいいだけなんだけどよく忘れるのでメモ

import logging
import traceback

try:
    def a():
        b()

    def b():
        open('./not_exist.txt')
    a()

except Exception, e:
    logging.error(traceback.format_exc())
    raise


出力

ERROR:root:Traceback (most recent call last):
  File "/Users/yuhei/workspace/sandbox/stacktrace_demo.py", line 10, in <module>
    a()
  File "/Users/yuhei/workspace/sandbox/stacktrace_demo.py", line 6, in a
    b()
  File "/Users/yuhei/workspace/sandbox/stacktrace_demo.py", line 9, in b
    open('./not_exist.txt')
IOError: [Errno 2] No such file or directory: './not_exist.txt'