-
Notifications
You must be signed in to change notification settings - Fork 562
feat(metrics): Add trace metrics behind an experiments flag #4898
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
sentrivana
merged 15 commits into
master
from
feat/tracemetrics/add-experimental-metrics
Oct 9, 2025
+576
−2
Merged
Changes from 1 commit
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
b156cff
feat(metrics): Add experimental trace metrics behind an experiments flag
k-fish 225affd
Cleanup exposing 'tracemetric' as users should only see 'metrics' sin…
k-fish c4f7052
Merge branch 'master' into feat/tracemetrics/add-experimental-metrics
sentrivana c25f7cb
renaming trace metrics -> metrics
sentrivana f339a60
Apply suggestion from @sentrivana
sentrivana f6bed30
add notice
sentrivana d8dd0ff
imports
sentrivana d7f64c4
fix flag name in tests
sentrivana e36c40b
fix type hint
sentrivana 63df412
move more stuff to client
sentrivana 92c8d41
fix setting trace_id
sentrivana 46f4691
propagation context test
sentrivana d87ae30
.
sentrivana 3301011
mypy
sentrivana 16a6058
better trace id check
sentrivana File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
import os | ||
import random | ||
import threading | ||
from datetime import datetime, timezone | ||
from typing import Optional, List, Callable, TYPE_CHECKING, Any | ||
|
||
from sentry_sdk.utils import format_timestamp, safe_repr | ||
from sentry_sdk.envelope import Envelope, Item, PayloadRef | ||
|
||
if TYPE_CHECKING: | ||
from sentry_sdk._types import TraceMetric | ||
|
||
|
||
class TraceMetricsBatcher: | ||
MAX_METRICS_BEFORE_FLUSH = 100 | ||
FLUSH_WAIT_TIME = 5.0 | ||
|
||
def __init__( | ||
self, | ||
capture_func, # type: Callable[[Envelope], None] | ||
): | ||
# type: (...) -> None | ||
self._metric_buffer = [] # type: List[TraceMetric] | ||
self._capture_func = capture_func | ||
self._running = True | ||
self._lock = threading.Lock() | ||
|
||
self._flush_event = threading.Event() # type: threading.Event | ||
|
||
self._flusher = None # type: Optional[threading.Thread] | ||
self._flusher_pid = None # type: Optional[int] | ||
|
||
def _ensure_thread(self): | ||
# type: (...) -> bool | ||
if not self._running: | ||
return False | ||
|
||
pid = os.getpid() | ||
if self._flusher_pid == pid: | ||
return True | ||
|
||
with self._lock: | ||
if self._flusher_pid == pid: | ||
return True | ||
|
||
self._flusher_pid = pid | ||
|
||
self._flusher = threading.Thread(target=self._flush_loop) | ||
self._flusher.daemon = True | ||
|
||
try: | ||
self._flusher.start() | ||
except RuntimeError: | ||
self._running = False | ||
return False | ||
|
||
return True | ||
|
||
def _flush_loop(self): | ||
# type: (...) -> None | ||
while self._running: | ||
self._flush_event.wait(self.FLUSH_WAIT_TIME + random.random()) | ||
self._flush_event.clear() | ||
self._flush() | ||
|
||
def add( | ||
self, | ||
metric, # type: TraceMetric | ||
): | ||
# type: (...) -> None | ||
if not self._ensure_thread() or self._flusher is None: | ||
return None | ||
|
||
with self._lock: | ||
self._metric_buffer.append(metric) | ||
if len(self._metric_buffer) >= self.MAX_METRICS_BEFORE_FLUSH: | ||
self._flush_event.set() | ||
|
||
def kill(self): | ||
# type: (...) -> None | ||
if self._flusher is None: | ||
return | ||
|
||
self._running = False | ||
self._flush_event.set() | ||
self._flusher = None | ||
|
||
def flush(self): | ||
# type: (...) -> None | ||
self._flush() | ||
|
||
@staticmethod | ||
def _metric_to_transport_format(metric): | ||
# type: (TraceMetric) -> Any | ||
def format_attribute(val): | ||
# type: (int | float | str | bool) -> Any | ||
sentrivana marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if isinstance(val, bool): | ||
return {"value": val, "type": "boolean"} | ||
if isinstance(val, int): | ||
return {"value": val, "type": "integer"} | ||
if isinstance(val, float): | ||
return {"value": val, "type": "double"} | ||
if isinstance(val, str): | ||
return {"value": val, "type": "string"} | ||
return {"value": safe_repr(val), "type": "string"} | ||
|
||
res = { | ||
"timestamp": metric["timestamp"], | ||
"trace_id": metric["trace_id"], | ||
"name": metric["name"], | ||
"type": metric["type"], | ||
"value": metric["value"], | ||
"attributes": { | ||
k: format_attribute(v) for (k, v) in metric["attributes"].items() | ||
}, | ||
} | ||
|
||
if metric.get("span_id") is not None: | ||
res["span_id"] = metric["span_id"] | ||
|
||
if metric.get("unit") is not None: | ||
res["unit"] = metric["unit"] | ||
|
||
return res | ||
|
||
def _flush(self): | ||
# type: (...) -> Optional[Envelope] | ||
|
||
envelope = Envelope( | ||
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} | ||
) | ||
with self._lock: | ||
if len(self._metric_buffer) == 0: | ||
return None | ||
|
||
envelope.add_item( | ||
Item( | ||
type="trace_metric", | ||
content_type="application/vnd.sentry.items.trace-metric+json", | ||
headers={ | ||
"item_count": len(self._metric_buffer), | ||
}, | ||
payload=PayloadRef( | ||
json={ | ||
"items": [ | ||
self._metric_to_transport_format(metric) | ||
for metric in self._metric_buffer | ||
] | ||
} | ||
), | ||
) | ||
) | ||
self._metric_buffer.clear() | ||
|
||
self._capture_func(envelope) | ||
return envelope | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.