Skip to content

add transaction name to error objects #1441

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

Merged
merged 3 commits into from
Jan 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ endif::[]
[float]
===== Features
* use "unknown-python-service" as default service name if no service name is configured {pull}1438[#1438]

* add transaction name to error objects {pull}1441[#1441]

[[release-notes-6.x]]
=== Python Agent version 6.x
Expand Down
6 changes: 5 additions & 1 deletion elasticapm/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,11 @@ def _build_msg_for_logging(
# parent id might already be set in the handler
event_data.setdefault("parent_id", span.id if span else transaction.id)
event_data["transaction_id"] = transaction.id
event_data["transaction"] = {"sampled": transaction.is_sampled, "type": transaction.transaction_type}
event_data["transaction"] = {
"sampled": transaction.is_sampled,
"type": transaction.transaction_type,
"name": transaction.name,
}

return event_data

Expand Down
39 changes: 23 additions & 16 deletions elasticapm/contrib/django/middleware/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@

import logging
import threading
from types import FunctionType
from typing import Optional

from django.apps import apps
from django.conf import settings as django_settings
from django.http import HttpRequest, HttpResponse

import elasticapm
from elasticapm.conf import constants
Expand Down Expand Up @@ -114,10 +117,10 @@ def process_response_wrapper(wrapped, instance, args, kwargs):
response = wrapped(*args, **kwargs)
try:
request, original_response = args
# if there's no view_func on the request, and this middleware created
# if we haven't set the name in a view, and this middleware created
# a new response object, it's logged as the responsible transaction
# name
if not hasattr(request, "_elasticapm_view_func") and response is not original_response:
if not getattr(request, "_elasticapm_name_set", False) and response is not original_response:
elasticapm.set_transaction_name(
build_name_with_http_method_prefix(get_name_from_middleware(wrapped, instance), request)
)
Expand Down Expand Up @@ -159,25 +162,17 @@ def instrument_middlewares(self):
except ImportError:
client.logger.warning("Can't instrument middleware %s", middleware_path)

def process_view(self, request, view_func, view_args, view_kwargs):
request._elasticapm_view_func = view_func
def process_view(self, request: HttpRequest, view_func: FunctionType, view_args: list, view_kwargs: dict):
elasticapm.set_transaction_name(self.get_transaction_name(request, view_func), override=False)
request._elasticapm_name_set = True

def process_response(self, request, response):
def process_response(self, request: HttpRequest, response: HttpResponse):
if django_settings.DEBUG and not self.client.config.debug:
return response
try:
if hasattr(response, "status_code"):
transaction_name = None
if self.client.config.django_transaction_name_from_route and hasattr(request.resolver_match, "route"):
r = request.resolver_match
# if no route is defined (e.g. for the root URL), fall back on url_name and then function name
transaction_name = r.route or r.url_name or get_name_from_func(r.func)
elif getattr(request, "_elasticapm_view_func", False):
transaction_name = get_name_from_func(request._elasticapm_view_func)
if transaction_name:
transaction_name = build_name_with_http_method_prefix(transaction_name, request)
elasticapm.set_transaction_name(transaction_name, override=False)

if not getattr(request, "_elasticapm_name_set", False):
elasticapm.set_transaction_name(self.get_transaction_name(request), override=False)
elasticapm.set_context(
lambda: self.client.get_data_from_request(request, constants.TRANSACTION), "request"
)
Expand All @@ -191,6 +186,18 @@ def process_response(self, request, response):
self.client.error_logger.error("Exception during timing of request", exc_info=True)
return response

def get_transaction_name(self, request: HttpRequest, view_func: Optional[FunctionType] = None) -> str:
transaction_name = ""
if self.client.config.django_transaction_name_from_route and hasattr(request.resolver_match, "route"):
r = request.resolver_match
# if no route is defined (e.g. for the root URL), fall back on url_name and then function name
transaction_name = r.route or r.url_name or get_name_from_func(r.func)
elif view_func:
transaction_name = get_name_from_func(view_func)
if transaction_name:
transaction_name = build_name_with_http_method_prefix(transaction_name, request)
return transaction_name


class ErrorIdMiddleware(MiddlewareMixin):
"""
Expand Down
46 changes: 46 additions & 0 deletions tests/contrib/django/django_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,52 @@ def test_transaction_metrics_error(django_elasticapm_client, client):
assert transaction["outcome"] == "failure"


def test_transaction_metrics_exception(django_elasticapm_client, client):
with override_settings(
**middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"])
):
assert len(django_elasticapm_client.events[TRANSACTION]) == 0
try:
client.get(reverse("elasticapm-raise-exc"))
except Exception:
pass
assert len(django_elasticapm_client.events[TRANSACTION]) == 1

transactions = django_elasticapm_client.events[TRANSACTION]
errors = django_elasticapm_client.events[ERROR]

assert len(transactions) == 1
assert len(errors) == 1
transaction = transactions[0]
error = errors[0]
assert transaction["duration"] > 0
assert transaction["result"] == "HTTP 5xx"
assert transaction["name"] == "GET tests.contrib.django.testapp.views.raise_exc"
assert transaction["outcome"] == "failure"
assert transaction["name"] == error["transaction"]["name"]


def test_transaction_metrics_404(django_elasticapm_client, client):
with override_settings(
**middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"])
):
assert len(django_elasticapm_client.events[TRANSACTION]) == 0
try:
r = client.get("/non-existant-url")
except Exception as e:
pass
assert len(django_elasticapm_client.events[TRANSACTION]) == 1

transactions = django_elasticapm_client.events[TRANSACTION]

assert len(transactions) == 1
transaction = transactions[0]
assert transaction["duration"] > 0
assert transaction["result"] == "HTTP 4xx"
assert transaction["name"] == ""
assert transaction["outcome"] == "success"


def test_transaction_metrics_debug(django_elasticapm_client, client):
with override_settings(
DEBUG=True, **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"])
Expand Down
4 changes: 2 additions & 2 deletions tests/contrib/django/testapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

import django
from django.conf import settings
from django.http import HttpResponse
from django.http import HttpResponseServerError

from tests.contrib.django.testapp import views

Expand All @@ -46,7 +46,7 @@
def handler500(request):
if getattr(settings, "BREAK_THAT_500", False):
raise ValueError("handler500")
return HttpResponse("")
return HttpResponseServerError("")


urlpatterns = (
Expand Down