cknd / stackprinter

Debugging-friendly exceptions for Python
MIT License
1.28k stars 37 forks source link

Stackprinter doesn't work with Django #44

Closed amir511 closed 3 years ago

amir511 commented 3 years ago

After installing stackprinter globally, as well as in the django project virtualenvironment And added sitecustomizations.py in the correct paths with the following code:

import stackprinter
stackprinter.set_excepthook(style='lightbg')

Still django errors are shown in the conventional style. Any other standalone script shows the stackprinter style. Any help on how to make it work for django?

cknd commented 3 years ago

sounds like django is handling the exceptions internally so they never reach the systemwide excepthook, so it's never reached. I know nothing about django, but here is one possible pointer how to hook a custom error logging function into it. https://stackoverflow.com/questions/13284890/python-django-automatically-log-when-exceptions-occur-including-request-info I'd google for django custom exception handler or django excepthook

cknd commented 3 years ago

(I'm closing this because exceptions that get caught by other libraries before they reach stackprinter are something I can't fix from my side)

amir511 commented 3 years ago

Hi @cknd , thanks for your reply and sorry for not following up on this. I have found a way to make it work for django, this can be done by creating a middleware to catch exceptions through stackprinter, plus a little extra work in django settings file. I am keen to add this functionality to stackprinter to work out of the box for django projects, so I was thinking to submit a pull request having the required changes. let me know if this works for you

gasull commented 6 months ago

I have found a way to make it work for django, this can be done by creating a middleware to catch exceptions through stackprinter, plus a little extra work in django settings file.

@amir511 , could you please paste your solution here? I haven't been able to make it work.

gasull commented 6 months ago

I found the solution:

# stackprinter_middleware.py
import stackprinter
import sys

class StackPrinterMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_exception(self, request, exception):
        stack_trace = stackprinter.format(
                exception,
                style="lightbg",
                suppressed_paths=[sys.prefix]
        )
        print(stack_trace, file=sys.stderr)
        raise exception

And at the end of settings.py:

MIDDLEWARE.insert(
    0,
    'superlists.stackprinter_middleware.StackPrinterMiddleware'
)
DEBUG_PROPAGATE_EXCEPTIONS = True
gasull commented 6 months ago

Maybe this could be added to the README, or be added to a contrib directory.