开发者

Print a stack trace to stdout on errors in Django while using manage.py runserver

开发者 https://www.devze.com 2023-03-03 11:54 出处:网络
I did some searching, but I\'m wondering if anyone has a snippet of a logging configuration to get Django to just output a stack trace to stdout (so I can see it in the Terminal window) when it encoun

I did some searching, but I'm wondering if anyone has a snippet of a logging configuration to get Django to just output a stack trace to stdout (so I can see it in the Terminal window) when it encounters an error during a request. This is speci开发者_如何学运维fically for local development/debugging and mainly for when I do AJAX post requests and I have to look at the HTML in Firebug to figure out what line the error occurred on.


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.


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


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.


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):
    ....


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...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消