Sending traceback with Django Ninja
Question
Is it possible to send traceback along with the log? I am using Django.
This is the log I want to send along with with the log
Simulate unhandled exception
Traceback (most recent call last):
File "/workspaces/gateway/.venv/lib/python3.12/site-packages/ninja/operation.py", line 120, in run
result = self.view_func(request, **values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/workspaces/gateway/app/appcore/routes/sample.py", line 135, in get_simulate_unhandled_exception
raise Exception("Simulate unhandled exception")
Exception: Simulate unhandled exception
With plain Django this already works. It seems that your problem is specific to Ninja. This seems to work:
from ninja import NinjaAPI
import logfire
api = NinjaAPI()
original_handler = api._lookup_exception_handler(Exception())
@api.exception_handler(Exception)
def validation_errors(request, exc):
logfire.exception('Unhandled exception')
return original_handler(request, exc)
Thank you! I couldn't get it to work with the current setup, will investigate more based on your suggestions.
The team got it working thank you!
Edited topic for clarity in case other people have the same issue.
Reopening because this should probably be incorporated into the SDK.
Also note that instead of logfire.exception('Unhandled exception') you could try:
from opentelemetry.trace import get_current_span
get_current_span().record_exception(exc)
which should put the exception directly on the request span instead of creating a child log. Does that work better?