From 1e361e41871285862a9dfd01a2fc5c207e9be410 Mon Sep 17 00:00:00 2001 From: Lily Mara <54288692+lilymara-onesignal@users.noreply.github.com> Date: Tue, 25 May 2021 14:34:46 -0700 Subject: [PATCH] opentelemetry: add opentelemetry source code attributes to spans (#1411) 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 Co-authored-by: Lily Mara --- tracing-opentelemetry/src/layer.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tracing-opentelemetry/src/layer.rs b/tracing-opentelemetry/src/layer.rs index e2d3033e3d..7d24d5b025 100644 --- a/tracing-opentelemetry/src/layer.rs +++ b/tracing-opentelemetry/src/layer.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); }