logfire icon indicating copy to clipboard operation
logfire copied to clipboard

Sending traceback with Django Ninja

Open Lodimup opened this issue 1 year ago • 4 comments

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

Lodimup avatar Mar 12 '25 11:03 Lodimup

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)

alexmojaki avatar Mar 12 '25 12:03 alexmojaki

Thank you! I couldn't get it to work with the current setup, will investigate more based on your suggestions.

Lodimup avatar Mar 12 '25 13:03 Lodimup

The team got it working thank you!

Edited topic for clarity in case other people have the same issue.

Lodimup avatar Mar 13 '25 03:03 Lodimup

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?

alexmojaki avatar Mar 13 '25 09:03 alexmojaki