-
Notifications
You must be signed in to change notification settings - Fork 223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix transaction tracing when running Django under ASGI #1953
Comments
We encountered this bug after updating to Django 5.0. We also run django in ASGI mode. In Django 4.x, transaction tracing worked fine, even in ASGI mode. |
I have encountered this as well in Django 5.0. When I call the following within my view class import elasticapm
elasticapm.label(obj_id='id') I get this message: |
Created a new django 5.0.6 project. Added in settings.py:
Added in views:
In urls.py:
in asgi.py:
run it via And got |
Thank you @xrmx doing that and extending your code fixed the issues I was having. I adapted your solution to use a custom middleware as I had a lot of URLs to monitor. I have found that the config option middleware.py import elasticapm
from elasticapm.contrib.django.middleware import TracingMiddleware
class CustomTracingMiddleware(TracingMiddleware):
def process_request(self, request: HttpRequest):
if elasticapm.get_transaction_id():
transaction_name: str = "{} {}".format(request.method.upper(), request.path.lower()) #type: ignore
elasticapm.set_transaction_name(transaction_name) #type: ignore
return None asgi.py from elasticapm.contrib.asgi import ASGITracingMiddleware
class CustomASGITracingMiddleware(ASGITracingMiddleware):
def get_url(self, scope, host: str | None = None) -> Tuple[str, dict[str, str]]:
_, url_dict = super().get_url(scope, host)
path = scope.get("root_path", "") + scope.get("path", "")
return path, url_dict
application = CustomASGITracingMiddleware(get_asgi_application()) settings.py MIDDLEWARE = [
'ehs_api.middleware.CustomTracingMiddleware',
# add others here
]
ELASTIC_APM = {
'SERVICE_NAME': 'djangoapm',
'SERVER_URL': '',
'DEBUG': True, #allows it to run in test mode
'TRANSACTION_IGNORE_URLS': [
'/__debug__/*',
],
'DJANGO_TRANSACTION_NAME_FROM_ROUTE': True,
'DJANGO_AUTOINSERT_MIDDLEWARE': False
} |
(Moved from original discussion)
When running Django under ASGI, the middleware that Elastic APM injects is not tracking standard Django request transactions.
Here's my
asgi.py
:My
settings.ELASTIC_APM
:I've browsed several pages and waited for Fleet to flush but all I see are Celery tasks:
Nothing is logged as a
request
transaction type by the standard Django middleware when running under Daphne.If I switch the project back to standard WSGI/Django runserver, it logs request transactions:
The text was updated successfully, but these errors were encountered: