Когда в приложении Flask возникают исключения, я хочу иметь возможность использовать cgitb для расширенного ведения журнала трассировки при возникновении исключений.
Просто выполните
import cgitb
cgitb.enable(format="text")
в верхней части файла, гдеприложение инициализировано не делает трюк.Я все еще получаю стандартную трассировку Python, когда возникает исключение.
Может быть проблема, вызванная тем, как у меня в настоящее время настроено ведение журнала в моем приложении, но я не смог выяснить это.
app = Flask(__name__)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:% (message)s'))
app.logger.addHandler(streamHandler)
app.logger.setLevel(logging.DEBUG)
@app.route('/')
def main_route():
a = 0
b = 2
c = b / 2
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Я ожидаю, что результаты трассировки будут такими:
$ python3 cgitb_local_vars.py
ZeroDivisionError
Python 3.7.1: .../bin/python3
Sun Dec 9 10:46:17 2018
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they
occurred.
.../cgitb_local_vars.py in <module>()
18 def func1(a, b):
19 c = b - 5
20 return func2(a, c)
21
22 func1(1, 5)
func1 = <function func1>
.../cgitb_local_vars.py in func1(a=1, b=5)
18 def func1(a, b):
19 c = b - 5
20 return func2(a, c)
21
22 func1(1, 5)
global func2 = <function func2>
a = 1
c = 0
.../cgitb_local_vars.py in func2(a=1, divisor=0)
13
14 def func2(a, divisor):
15 return a / divisor
16
17
a = 1
divisor = 0
ZeroDivisionError: division by zero
__cause__ = None
__class__ = <class 'ZeroDivisionError'>
__context__ = None
__delattr__ = <method-wrapper '__delattr__' of
ZeroDivisionError object>
__dict__ = {}
__dir__ = <built-in method __dir__ of ZeroDivisionError
object>
__doc__ = 'Second argument to a division or modulo operation
was zero.'
__eq__ = <method-wrapper '__eq__' of ZeroDivisionError
object>
__format__ = <built-in method __format__ of
ZeroDivisionError object>
__ge__ = <method-wrapper '__ge__' of ZeroDivisionError
object>
__getattribute__ = <method-wrapper '__getattribute__' of
ZeroDivisionError object>
__gt__ = <method-wrapper '__gt__' of ZeroDivisionError
object>
__hash__ = <method-wrapper '__hash__' of ZeroDivisionError
object>
__init__ = <method-wrapper '__init__' of ZeroDivisionError
object>
__init_subclass__ = <built-in method __init_subclass__ of
type object>
__le__ = <method-wrapper '__le__' of ZeroDivisionError
object>
__lt__ = <method-wrapper '__lt__' of ZeroDivisionError
object>
__ne__ = <method-wrapper '__ne__' of ZeroDivisionError
object>
__new__ = <built-in method __new__ of type object>
__reduce__ = <built-in method __reduce__ of
ZeroDivisionError object>
__reduce_ex__ = <built-in method __reduce_ex__ of
ZeroDivisionError object>
__repr__ = <method-wrapper '__repr__' of ZeroDivisionError
object>
__setattr__ = <method-wrapper '__setattr__' of
ZeroDivisionError object>
__setstate__ = <built-in method __setstate__ of
ZeroDivisionError object>
__sizeof__ = <built-in method __sizeof__ of
ZeroDivisionError object>
__str__ = <method-wrapper '__str__' of ZeroDivisionError
object>
__subclasshook__ = <built-in method __subclasshook__ of type
object>
__suppress_context__ = False
__traceback__ = <traceback object>
args = ('division by zero',)
with_traceback = <built-in method with_traceback of
ZeroDivisionError object>
The above is a description of an error in a Python program.
Here is
the original traceback:
Traceback (most recent call last):
File "cgitb_local_vars.py", line 22, in <module>
func1(1, 5)
File "cgitb_local_vars.py", line 20, in func1
return func2(a, c)
File "cgitb_local_vars.py", line 15, in func2
return a / divisor
ZeroDivisionError: division by zero
Демонстрационный код
from flask import Flask
import cgitb
import logging
import sys
cgitb.enable(format="text")
app = Flask(__name__)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:% (message)s'))
app.logger.addHandler(streamHandler)
app.logger.setLevel(logging.DEBUG)
@app.before_request
def before_request():
a = 0
b = 2
c = b / a
@app.route('/')
def main_page():
a = 0
b = 2
c = b / a
return 'Success'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5005, debug=True)
Результат
Connected to pydev debugger (build 182.4505.18)
* Serving Flask app "flask_app_demo" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)
* Restarting with stat
pydev debugger: process 36941 is connecting
* Debugger is active!
* Debugger PIN: 334-725-940
10.81.19.181 - - [30/Jan/2019 17:46:47] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
File "/python/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/python/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/python/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/python/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/python/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/python/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/python/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/python/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/python/site-packages/flask/app.py", line 1811, in full_dispatch_request
rv = self.preprocess_request()
File "/python/site-packages/flask/app.py", line 2087, in preprocess_request
rv = func()
File "/flask_app_demo.py", line 18, in before_request
from _pydev_bundle import fix_getpass
ZeroDivisionError: division by zero