1

How can I get the stack trace when something fails on the server side in the django middleware? Here is what I've tried that only gives me the message, not the full stack.

class MonitorMiddleware(object):
    def process_exception(self, request, exception):
        self.error = exception.message
max
  • 9,708
  • 15
  • 89
  • 144
  • Possibly duplicate? https://stackoverflow.com/questions/11414894/extract-traceback-info-from-an-exception-object – Risadinha Mar 20 '19 at 20:38

1 Answers1

0

Answer to "retrieve the error stack trace to save to the database" from comment:

https://docs.python.org/3/library/traceback.html

Use the methods of traceback to convert the trace of the exception into a string which you can then store in the database.

Also on the above page:

New in version 3.5.

StackSummary objects represent a call stack ready for formatting.

The short short example with an exception object:

>>> an_error = IndexError('tuple index out of range')
>>> traceback.print_exception(type(an_error), an_error, an_error.__traceback__)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

See also Extract traceback info from an exception object: You don't need to re-raise the exception, though, the traceback is in the __traceback__ attribute.

Risadinha
  • 16,058
  • 2
  • 88
  • 91
  • Hi. I'm not trying to insert information into the logs; I'm trying to retrieve the error stack trace to save to the database for example something goes wrong in a view or controller and the middleware records it in the database . – max Mar 20 '19 at 20:19
  • uh, I don't know why I thought it does not work...I used traceback.format_exc() – max Mar 20 '19 at 20:43