Skip to content

Commit 7195f62

Browse files
authored
1 parent a5523ae commit 7195f62

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/api/trace/span.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use crate::api;
1919
#[cfg(feature = "serialize")]
2020
use serde::{Deserialize, Serialize};
21+
use std::error::Error;
2122
use std::fmt;
2223
use std::time::SystemTime;
2324

@@ -38,6 +39,40 @@ pub trait Span: fmt::Debug + 'static + Send + Sync {
3839
self.add_event_with_timestamp(name, SystemTime::now(), attributes)
3940
}
4041

42+
/// Convenience method to record an exception/error as an `Event`
43+
///
44+
/// An exception SHOULD be recorded as an Event on the span during which it occurred.
45+
/// The name of the event MUST be "exception".
46+
///
47+
/// The semantic conventions for Errors are described in ["Semantic Conventions for Exceptions"](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/exceptions.md)
48+
///
49+
/// For now we will not set `exception.stacktrace` attribute since the `Error::backtrace`
50+
/// method is still in nightly. Users can provide a stacktrace by using the
51+
/// `record_exception_with_stacktrace` method.
52+
///
53+
/// Users can custom the exception message by overriding the `fmt::Display` trait's `fmt` method
54+
/// for the error.
55+
fn record_exception(&self, err: &dyn Error) {
56+
let attributes = vec![api::KeyValue::new(
57+
"exception.message",
58+
err.to_string(),
59+
)];
60+
61+
self.add_event("exception".to_string(), attributes);
62+
}
63+
64+
/// Convenience method to record a exception/error as an `Event` with custom stacktrace
65+
///
66+
/// See `Span:record_exception` method for more details.
67+
fn record_exception_with_stacktrace(&self, err: &dyn Error, stacktrace: String) {
68+
let attributes = vec![api::KeyValue::new(
69+
"exception.message",
70+
err.to_string(),
71+
), api::KeyValue::new("exception.stacktrace", stacktrace)];
72+
73+
self.add_event("exception".to_string(), attributes);
74+
}
75+
4176
/// An API to record events at a specific time in the context of a given `Span`.
4277
///
4378
/// Events SHOULD preserve the order in which they're set. This will typically match

0 commit comments

Comments
 (0)