Skip to content
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
5 changes: 5 additions & 0 deletions .sampo/changesets/capture-exception-otel-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

Add the active OpenTelemetry span's `$trace_id` and `$span_id` to events captured with `capture_exception`.
5 changes: 5 additions & 0 deletions posthog/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
exc_info_from_error,
exception_is_already_captured,
exceptions_from_error_tuple,
_get_current_otel_span_properties,
handle_in_app,
mark_exception_as_captured,
try_attach_code_variables_to_frames,
Expand Down Expand Up @@ -1405,6 +1406,9 @@ def capture_exception(
"""
Capture an exception for error tracking.

When OpenTelemetry is installed and a valid span is active, its trace and
span IDs are added as ``$trace_id`` and ``$span_id`` event properties.

Args:
exception: The exception to capture.
distinct_id: The distinct ID of the user.
Expand Down Expand Up @@ -1467,6 +1471,7 @@ def capture_exception(

properties = {
"$exception_list": all_exceptions_with_trace_and_in_app,
**_get_current_otel_span_properties(),
**properties,
}

Expand Down
18 changes: 18 additions & 0 deletions posthog/exception_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,24 @@
)


def _get_current_otel_span_properties() -> Dict[str, str]:
try:
from opentelemetry import trace
except ImportError:
return {}

try:
span_context = trace.get_current_span().get_span_context()
if not span_context.is_valid:
return {}
return {
"$trace_id": f"{span_context.trace_id:032x}",
"$span_id": f"{span_context.span_id:016x}",
}
except Exception:
return {}


def _redact_url_credentials(value):
if "://" not in value:
return value
Expand Down
55 changes: 54 additions & 1 deletion posthog/test/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
import unittest
import warnings
from datetime import datetime
from unittest import mock
from uuid import UUID, uuid4

from unittest import mock
from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags, use_span
from parameterized import parameterized

from posthog.capture_compression import CaptureCompression
Expand Down Expand Up @@ -487,6 +488,58 @@ def test_basic_capture_exception(self):
self.assertEqual(capture_call[0][0], "$exception")
self.assertEqual(capture_call[1]["distinct_id"], "distinct_id")

@parameterized.expand(
[
(
"active_context",
0x123,
0x456,
{},
"00000000000000000000000000000123",
"0000000000000456",
),
(
"explicit_properties",
0x123,
0x456,
{"$trace_id": "custom-trace", "$span_id": "custom-span"},
"custom-trace",
"custom-span",
),
("invalid_context", 0, 0, {}, None, None),
]
)
def test_capture_exception_uses_current_otel_span_context(
self,
_,
context_trace_id,
context_span_id,
properties,
expected_trace_id,
expected_span_id,
):
span_context = SpanContext(
trace_id=context_trace_id,
span_id=context_span_id,
is_remote=False,
trace_flags=TraceFlags.SAMPLED,
)

with (
mock.patch("posthog.client.batch_post") as mock_post,
use_span(NonRecordingSpan(span_context)),
):
client = Client(FAKE_TEST_API_KEY, sync_mode=True)
client.capture_exception(Exception("test exception"), properties=properties)

event = mock_post.call_args.kwargs["batch"][0]
if expected_trace_id is None:
self.assertNotIn("$trace_id", event["properties"])
self.assertNotIn("$span_id", event["properties"])
else:
self.assertEqual(event["properties"]["$trace_id"], expected_trace_id)
self.assertEqual(event["properties"]["$span_id"], expected_span_id)

def test_basic_capture_exception_with_distinct_id(self):
with mock.patch.object(Client, "capture", return_value=None) as patch_capture:
client = self.client
Expand Down
Loading