M
M
max2019-11-17 11:41:55
Django
max, 2019-11-17 11:41:55

How to handle all (including those from other threads) exceptions in Django?

I need to log all the errors that happened in the project. Especially the ones that happened in other threads.
In flask, this is done by specifying an error handler:

app.register_error_handler(Exception, _error_handler)

def _error_handler(error):
  log.exception(error)

I did not find something similar in django. I decided to do it through middleware:
# middleware.py:
class LoggingExceptionMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        logger.error('LoggingExceptionMiddleware.process_exception was called')
        logger.exception(exception)


# views.py
def exception(request):
    raise Exception('bla bla')


def exception_in_new_thread(request):
    logger.debug('exception_in_new_thread called')
    Thread(target=buggy_func).start()
    return HttpResponse('ok')


def buggy_func():
    logger.debug('buggy_func called')
    sleep(5)
    raise Exception('hi from buggy_func')

But this trick didn't work. If an error occurs in a django thread (def exception), then the middleware is triggered. But if in another thread (exception_in_new_thread), then the error is not caught.
How do you log _ALL_ exceptions that happen in a project?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2019-11-17
@sergey-gornostaev

I did not find something similar in django.

Django is designed to be synchronous and single threaded. Streams should not be used in it.

D
Dr. Bacon, 2019-11-17
@bacon

Options
1. Abandon Thread in django, they don't make much sense, it's better to put such tasks in the job queue
2. Handle all exceptions inside the Thread, wrap it in a decorator for simplicity.

A
alternativshik, 2019-11-17
@alternativshik

+ to everything above https://docs.djangoproject.com/en/2.2/topics/logging/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question