Skip to content

Commit

Permalink
Display attribute in metrics (#85)
Browse files Browse the repository at this point in the history
## Motivation

As described in #81, currently the metrics layer doesn't do anything
when Debug / Display values are given.

## Solution

Record `Debug` attributes as otel metric attributes.
  • Loading branch information
KentaKudo authored Jan 23, 2024
1 parent b2013d0 commit 832b788
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,9 @@ pub(crate) struct MetricVisitor<'a> {
}

impl<'a> Visit for MetricVisitor<'a> {
fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {
// Do nothing
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.attributes
.push(KeyValue::new(field.name(), format!("{value:?}")));
}

fn record_u64(&mut self, field: &Field, value: u64) {
Expand Down
62 changes: 62 additions & 0 deletions tests/metrics_publishing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,68 @@ async fn f64_histogram_with_attributes_is_exported() {
exporter.export().unwrap();
}

#[tokio::test]
async fn display_attribute_is_exported() {
let (subscriber, exporter) = init_subscriber(
"hello_world".to_string(),
InstrumentKind::Counter,
1_u64,
Some(AttributeSet::from(
[KeyValue::new("display_key_1", "display: foo")].as_slice(),
)),
);

struct DisplayAttribute(String);

impl std::fmt::Display for DisplayAttribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "display: {}", self.0)
}
}

let display_attribute = DisplayAttribute("foo".to_string());

tracing::subscriber::with_default(subscriber, || {
tracing::info!(
monotonic_counter.hello_world = 1_u64,
display_key_1 = %display_attribute,
);
});

exporter.export().unwrap();
}

#[tokio::test]
async fn debug_attribute_is_exported() {
let (subscriber, exporter) = init_subscriber(
"hello_world".to_string(),
InstrumentKind::Counter,
1_u64,
Some(AttributeSet::from(
[KeyValue::new("debug_key_1", "debug: foo")].as_slice(),
)),
);

struct DebugAttribute(String);

impl std::fmt::Debug for DebugAttribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "debug: {}", self.0)
}
}

let debug_attribute = DebugAttribute("foo".to_string());

tracing::subscriber::with_default(subscriber, || {
tracing::info!(
monotonic_counter.hello_world = 1_u64,
debug_key_1 = ?debug_attribute,
);
});

exporter.export().unwrap();
}

fn init_subscriber<T>(
expected_metric_name: String,
expected_instrument_kind: InstrumentKind,
Expand Down

0 comments on commit 832b788

Please sign in to comment.