From 7f8c4395077c0efeda43db23e9b45a504d8cfd6e Mon Sep 17 00:00:00 2001 From: Lily Mara Date: Wed, 19 May 2021 14:57:37 -0700 Subject: [PATCH] Add opentelemetry source code attributes to spans The opentelemetry specification calls for a number of attributes to correlate traces to their location in the code. They are documented here [1]. This commit adds support for the following fields based on the tracing span metadata (all relative to span creation): - `code.namespace`: Crate & module path (`my_crate::my_mod`) - `code.filepath`: Relative path to the source code file (`src/my_mod.rs`) - `code.lineno`: Line number in the file indicated by `code.filepath` (`72`) As written this will annotate all spans with these attributes. If we want to be a bit more conservative, I could add an instance variable to the Subscriber that allows users to opt-in or opt-out of this functionality. [1]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/span-general.md#source-code-attributes --- tracing-opentelemetry/src/subscriber.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tracing-opentelemetry/src/subscriber.rs b/tracing-opentelemetry/src/subscriber.rs index cb38b8318a..40cda883e2 100644 --- a/tracing-opentelemetry/src/subscriber.rs +++ b/tracing-opentelemetry/src/subscriber.rs @@ -421,6 +421,22 @@ where builder.trace_id = Some(self.tracer.new_trace_id()); } + let builder_attrs = builder.attributes.get_or_insert(Vec::new()); + + let meta = attrs.metadata(); + + if let Some(filename) = meta.file() { + builder_attrs.push(KeyValue::new("code.filepath", filename)); + } + + if let Some(module) = meta.module_path() { + builder_attrs.push(KeyValue::new("code.namespace", module)); + } + + if let Some(line) = meta.line() { + builder_attrs.push(KeyValue::new("code.lineno", line as i64)); + } + attrs.record(&mut SpanAttributeVisitor(&mut builder)); extensions.insert(builder); }