25👍
You can create a piece of middleware to do this. Here’s a modified snippet I’m using for a project:
class ExceptionLoggingMiddleware(object):
def process_exception(self, request, exception):
import traceback
print traceback.format_exc()
Place this handler in your middleware part of the Django settings.
37👍
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.
- [Django]-Django: adding an "Add new" button for a ForeignKey in a ModelForm
- [Django]-Proper way to bulk_create for ManyToMany field, Django?
- [Django]-Update only specific fields in a models.Model
28👍
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
- [Django]-Django-rest-framework 3.0 create or update in nested serializer
- [Django]-Celery discover tasks in files with other filenames
- [Django]-How to insert data to django database from views.py file?
3👍
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:
def log_errors(func):
if not settings.DEBUG:
return func
def wrapper(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):
....
- [Django]-How to make Django QuerySet bulk delete() more efficient
- [Django]-How do I return a 401 Unauthorized in Django?
- [Django]-How to force Django models to be released from memory
2👍
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…
- [Django]-Unsupported operand type(s) for *: 'float' and 'Decimal'
- [Django]-How to use 2 different cache backends in Django?
- [Django]-Django Unique Together (with foreign keys)
0👍
Subclass WSGI handler, do whatever you want with traceback in your defined handle_uncaught_exception
, and use your WSGIHandler instead of the one provided by django when deploying.
import traceback
from django.core.handlers.wsgi import WSGIHandler
class MyWSGIHandler(WSGIHandler):
"""WSGI Handler which prints traceback to stderr"""
def handle_uncaught_exception(self, request, resolver, exc_info):
traceback.print_tb(exc_info[2], file=sys.stderr)
return super(WSGIHandler, self).handle_uncaught_exception(request, resolver, exc_info)
Used with Apache/mod_wsgi, this should write traceback in Apache’s error log
- [Django]-CSRF Failed: CSRF token missing or incorrect
- [Django]-Supervising virtualenv django app via supervisor
- [Django]-Django+Postgres: "current transaction is aborted, commands ignored until end of transaction block"