Skip to content

Commit ef29d5b

Browse files
committed
opentelemetry: allocate fewer strings for recording events (#1917)
## Motivation Currently, the `tracing-opentelemetry` subscriber will allocate several strings for opentelemetry key-value fields in its `on_event` implementation. Some of these allocations are not necessary, since `opentelemetry::Value::String` can take a `Cow`, allowing `&'static str`s to be used without allocating a new `String`. Since this happens for _every_ event that's recorded to opentelemetry, this probably has a meaningful performance impact. ## Solution This branch makes two primary changes: + Change the `on_event` method to subscriber to use `&'static str`s for event targets when possible, similarly to how we did this for source locations in #1911. This way, when events were not recorded via the `tracing-log` adapter, we will use the `&'static` tracing metadata string for their targets, rather than allocating a new `String`. New `String`s are only allocated when an event came from the `log` crate and its target is not valid for the `'static` lifetime. * Use `Level::as_str` for the `Level` key-value field, instead of `Level::to_string`. `to_string` calls `fmt::Display` and returns a `String`, while `as_str` returns an `&'static str`. This way, levels will never allocate a `String`.
1 parent e0c86ee commit ef29d5b

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

tracing-opentelemetry/src/layer.rs

+14-4
Original file line numberDiff line numberDiff line change
@@ -554,13 +554,23 @@ where
554554
let meta = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());
555555
#[cfg(not(feature = "tracing-log"))]
556556
let meta = event.metadata();
557+
558+
let target = Key::new("target");
559+
560+
#[cfg(feature = "tracing-log")]
561+
let target = if normalized_meta.is_some() {
562+
target.string(meta.target().to_owned())
563+
} else {
564+
target.string(event.metadata().target())
565+
};
566+
567+
#[cfg(not(feature = "tracing-log"))]
568+
let target = target.string(meta.target());
569+
557570
let mut otel_event = otel::Event::new(
558571
String::new(),
559572
SystemTime::now(),
560-
vec![
561-
Key::new("level").string(meta.level().to_string()),
562-
Key::new("target").string(meta.target().to_string()),
563-
],
573+
vec![Key::new("level").string(meta.level().as_str()), target],
564574
0,
565575
);
566576
event.record(&mut SpanEventVisitor(&mut otel_event));

0 commit comments

Comments
 (0)