Skip to content

Commit 8e90d67

Browse files
authored
Always collect operation.cost metric in spans (#1435)
1 parent 12ccc6e commit 8e90d67

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

logfire/_internal/tracer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ def record_exception(
206206
record_exception(self.span, exception, attributes=attributes, timestamp=timestamp, escaped=escaped)
207207

208208
def increment_metric(self, name: str, attributes: Mapping[str, otel_types.AttributeValue], value: float) -> None:
209-
if not self.is_recording() or not self.record_metrics:
209+
if not (self.is_recording() and (self.record_metrics or name == 'operation.cost')):
210210
return
211211

212212
self.metrics[name].increment(attributes, value)

tests/test_metrics.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,48 @@ def test_metrics_in_spans(exporter: TestExporter):
438438
)
439439

440440

441+
def test_metrics_in_spans_disabled(exporter: TestExporter):
442+
# This method of setting collect_in_spans is a hack because using logfire.configure for this is annoying,
443+
# this way of doing it isn't guaranteed to work forever.
444+
metrics_options = logfire.DEFAULT_LOGFIRE_INSTANCE.config.metrics
445+
assert isinstance(metrics_options, logfire.MetricsOptions)
446+
metrics_options.collect_in_spans = False
447+
448+
# operation.cost is special cased to always be collected regardless of config
449+
cost = logfire.metric_counter('operation.cost')
450+
tokens = logfire.metric_counter('tokens') # not collected
451+
452+
with logfire.span('span'):
453+
tokens.add(100)
454+
cost.add(200)
455+
456+
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
457+
[
458+
{
459+
'name': 'span',
460+
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
461+
'parent': None,
462+
'start_time': 1000000000,
463+
'end_time': 2000000000,
464+
'attributes': {
465+
'code.filepath': 'test_metrics.py',
466+
'code.function': 'test_metrics_in_spans_disabled',
467+
'code.lineno': 123,
468+
'logfire.msg_template': 'span',
469+
'logfire.msg': 'span',
470+
'logfire.span_type': 'span',
471+
'logfire.metrics': {
472+
'operation.cost': {
473+
'details': [{'attributes': {}, 'total': 200}],
474+
'total': 200,
475+
}
476+
},
477+
},
478+
}
479+
]
480+
)
481+
482+
441483
def test_metrics_in_non_recording_spans(exporter: TestExporter, config_kwargs: dict[str, Any]):
442484
metrics_reader = InMemoryMetricReader(preferred_temporality=METRICS_PREFERRED_TEMPORALITY)
443485
logfire.configure(

0 commit comments

Comments
 (0)