I'm using the tracing library in my project and there is one thing I'm not able to figure out: How can I access a value (that I set in my span when I create it) in my Layer
?
My layer looks like this:
impl<S> Layer<S> for CustomLayer where S: Subscriber {
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
Interest::sometimes() //hardcoding so enabled() will be called everytime a span is created
}
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
if metadata.is_span() {
// How do I access value of key here?
if value == X {
true
} else if value == Y {
false
}
}
true // default
}
}
You can access the data in a
Span
if you have access to either itsValueSet
(as found innew_span()
oron_new_span()
viaAttributes
) or aRecord
entry for it (as found inrecord()
oron_record()
). With that you can use the visitor pattern to find the information you desire. Here's a simple implementation that checks if a field exists and its value is a matching string:This is pretty rudimentary but hopefully demonstrates what is possible. One thing to note is that the "value" that is stored is either a primitive value (
i64
,u64
,bool
,str
, etc.) or in a type-erased form via&dyn Debug
. Those are the only types of values you can receive from the visitor.Addressing OP's case in particular, as explained in this issue you cannot access this information in the
enabled()
method since that occurs before any values are recorded. You will need to make your determination in thenew_span()
method, and use span extensions via the registry to track whether you consider the span is "enabled" in your other methods.Here's another rudimentary example:
Note: I've completely rewritten this answer taking info from the comments and my newfound experience.