from django.http import HttpRequest, HttpResponse from django_components import Component, register, types from .component import analytics_events, error_rate class AnalyticsPage(Component): class Media: js = ("https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,container-queries",) template: types.django_html = """ {% load component_tags %} Analytics Example

Component Analytics

Track component errors or success rates to send them to Sentry or other services.

{# NOTE: Intentionally hidden so we focus on the events tracking #}
{% component "template_with_errors" / %}
{% component "captured_events" / %}
""" class View: def get(self, request: HttpRequest) -> HttpResponse: # Clear events on each page load analytics_events.clear() error_rate["error"] = 0 error_rate["success"] = 0 return AnalyticsPage.render_to_response(request=request) @register("template_with_errors") class TemplateWithErrors(Component): template: types.django_html = """

Sentry Error Tracking

This component only logs events when an error occurs.

{% component "error_fallback" %} {% component "sentry_error_tracker" %} {% component "api_widget" simulate_error=True / %} {% endcomponent %} {% endcomponent %} {% component "sentry_error_tracker" %} {% component "api_widget" simulate_error=False / %} {% endcomponent %}

Success Rate Analytics

This component logs both successful and failed renders.

{% component "error_fallback" %} {% component "success_rate_tracker" %} {% component "api_widget" simulate_error=True / %} {% endcomponent %} {% endcomponent %} {% component "success_rate_tracker" %} {% component "api_widget" simulate_error=False / %} {% endcomponent %}
""" # NOTE: Since this runs after `template_with_errors`, # the `analytics_events` will be populated. @register("captured_events") class CapturedEvents(Component): def get_template_data(self, args, kwargs, slots, context): return {"events": analytics_events, "error_rate": error_rate} template: types.django_html = """

Captured Analytics Events

                {% for event in events %}
                    {{ event }}
                {% endfor %}
            

Error Rate

                {{ error_rate }}
            

{{ error_rate.error }} errors out of {{ error_rate.success }} calls.

"""