skorokithakis / tbvaccine

A small utility to pretty-print Python tracebacks. ⛺
MIT License
377 stars 14 forks source link

How to integrate with flask or logging? #12

Closed guyskk closed 6 years ago

guyskk commented 7 years ago

It no effect when exception raised in flask request because the tracebacks are formatted by logging, the sys.excepthook is not called.

eg:

import tbvaccine
from flask import Flask

tbvaccine.add_hook(isolate=True)
app = Flask(__name__)

@app.route('/')
def index():
    return 1 / 0

if __name__ == '__main__':
    app.run()

the outputs:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2017-06-01 21:59:08,086] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/home/guyskk/.local/share/virtualenvs/next_passport-OfYZSIo0/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/guyskk/.local/share/virtualenvs/next_passport-OfYZSIo0/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/guyskk/.local/share/virtualenvs/next_passport-OfYZSIo0/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/guyskk/.local/share/virtualenvs/next_passport-OfYZSIo0/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/guyskk/.local/share/virtualenvs/next_passport-OfYZSIo0/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/guyskk/.local/share/virtualenvs/next_passport-OfYZSIo0/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 10, in index
    return 1 / 0
ZeroDivisionError: division by zero
127.0.0.1 - - [01/Jun/2017 21:59:08] "GET / HTTP/1.1" 500 -
afeblot commented 6 years ago

Logging integration:

class TbVaccineFormatter(logging.Formatter):
    def  formatException(self, exc_info):
        return TBVaccine(isolate=True).format_exc()

sh = logging.StreamHandler()
sh.setFormatter(TbVaccineFormatter('[%(levelname)s] %(asctime)s : %(message)s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(sh)
skorokithakis commented 6 years ago

Thank you, @afeblot. Would you mind issuing a PR to add that to the README? It's very useful.