Print A Stack Trace To Stdout On Errors In Django While Using Manage.py Runserver
Solution 1:
Another method is with LOGGING. Specifically you get a stacktrace when running ./manage.py runserver
by adding the following to the settings.py file:
LOGGING = {
'version': 1,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.request': {
'handlers':['console'],
'propagate': True,
'level':'DEBUG',
}
},
}
This syntax comes from the Django documentation Configuring Logging and can be further modified to increase or decrease the amount of console-logging.
Also the 5XX responses are raised as ERROR messages and 4XX responses are raised as WARNING messages.
Note that this question & answer has a 2013 duplicate here.
Solution 2:
It's strange nobody mentioned the DEBUG_PROPAGATE_EXCEPTIONS
setting. It's not for production, but very easy to use for at test/debugging environment. Simply add to settings.py
:
DEBUG_PROPAGATE_EXCEPTIONS = True
Solution 3:
You can create a piece of middleware to do this. Here's a modified snippet I'm using for a project:
classExceptionLoggingMiddleware(object):
defprocess_exception(self, request, exception):
import traceback
print traceback.format_exc()
Place this handler in your middleware part of the Django settings.
Solution 4:
I had a similar problem, but the middleware option didn't help me. The reason is that I'm using django-jsonview 0.4.3 which provides a decorator that converts a dictionary into a valid json http response, even when the decorated function fails, so process_exception middleware method is never called. I checked the code of this decorator and it seems that it tries to log the error doing this:
...
except Exception as e:
logger = logging.getLogger('django.request')
logger.exception(unicode(e))
However, I don't know why, this is not working and nothing is logged in my bash console. I should find out why this in happening. Meanwhile, I'm using an extra decorator:
deflog_errors(func):
ifnot settings.DEBUG:
return func
defwrapper(request, *args, **kwargs):
try:
return func(request, *args, **kwargs)
except:
print traceback.format_exc()
return wrapper
Then, in all my json views:
@json_view@log_errors
def my_view(request):
....
Solution 5:
I usually use this:
except Exception,e:
# Get line
trace=traceback.extract_tb(sys.exc_info()[2])
# Add the event to the log
output ="Error in the server: %s.\n"% (e)
output+="\tTraceback is:\n"for (file,linenumber,affected,line) in trace:
output+="\t> Error at function %s\n"% (affected)
output+="\t At: %s:%s\n"% (file,linenumber)
output+="\t Source: %s\n"% (line)
output+="\t> Exception: %s\n"% (e)
Then I use "output" for whatever I need: print to stdout, send an email, etc...
Post a Comment for "Print A Stack Trace To Stdout On Errors In Django While Using Manage.py Runserver"