Trait Subscriber
trait Subscriber: 'static
Trait representing the functions required to collect trace data.
Crates that provide implementations of methods for collecting or recording
trace data should implement the Subscriber interface. This trait is
intended to represent fundamental primitives for collecting trace events and
spans — other libraries may offer utility functions and types to make
subscriber implementations more modular or improve the ergonomics of writing
subscribers.
A subscriber is responsible for the following:
- Registering new spans as they are created, and providing them with span IDs. Implicitly, this means the subscriber may determine the strategy for determining span equality.
- Recording the attachment of field values and follows-from annotations to spans.
- Filtering spans and events, and determining when those filters must be invalidated.
- Observing spans as they are entered, exited, and closed, and events as they occur.
When a span is entered or exited, the subscriber is provided only with the
ID with which it tagged that span when it was created. This means
that it is up to the subscriber to determine whether and how span data —
the fields and metadata describing the span — should be stored. The
new_span function is called when a new span is created, and at that
point, the subscriber may choose to store the associated data if it will
be referenced again. However, if the data has already been recorded and will
not be needed by the implementations of enter and exit, the subscriber
may freely discard that data without allocating space to store it.
Overriding default impls
Some trait methods on Subscriber have default implementations, either in
order to reduce the surface area of implementing Subscriber, or for
backward-compatibility reasons. However, many subscribers will likely want
to override these default implementations.
The following methods are likely of interest:
-
register_callsiteis called once for each callsite from which a span event may originate, and returns anInterestvalue describing whether or not the subscriber wishes to see events or spans from that callsite. By default, it callsenabled, and returnsInterest::always()ifenabledreturns true, orInterest::never()if enabled returns false. However, if the subscriber's interest can change dynamically at runtime, it may want to override this function to returnInterest::sometimes(). Additionally, subscribers which wish to perform a behaviour once for each callsite, such as allocating storage for data related to that callsite, can perform it inregister_callsite.See also the documentation on the callsite registry for details on
register_callsite. -
event_enabledis called once before every call to theeventmethod. This can be used to implement filtering on events once their field values are known, but before any processing is done in theeventmethod. -
clone_spanis called every time a span ID is cloned, andtry_closeis called when a span ID is dropped. By default, these functions do nothing. However, they can be used to implement reference counting for spans, allowing subscribers to free storage for span data and to determine when a span has closed permanently (rather than being exited). Subscribers which store per-span data or which need to track span closures should override these functions together.
Required Methods
fn enabled(self: &Self, metadata: &Metadata<'_>) -> boolReturns true if a span or event with the specified metadata would be recorded.
By default, it is assumed that this filter needs only be evaluated once for each callsite, so it is called by
register_callsitewhen each callsite is registered. The result is used to determine if the subscriber is always interested or never interested in that callsite. This is intended primarily as an optimization, so that expensive filters (such as those involving string search, et cetera) need not be re-evaluated.However, if the subscriber's interest in a particular span or event may change, or depends on contexts only determined dynamically at runtime, then the
register_callsitemethod should be overridden to returnInterest::sometimes. In that case, this function will be called every time that span or event occurs.fn new_span(self: &Self, span: &Attributes<'_>) -> IdVisit the construction of a new span, returning a new span ID for the span being constructed.
The provided
Attributescontains any field values that were provided when the span was created. The subscriber may pass a visitor to theAttributes'recordmethod to record these values.IDs are used to uniquely identify spans and events within the context of a subscriber, so span equality will be based on the returned ID. Thus, if the subscriber wishes for all spans with the same metadata to be considered equal, it should return the same ID every time it is given a particular set of metadata. Similarly, if it wishes for two separate instances of a span with the same metadata to not be equal, it should return a distinct ID every time this function is called, regardless of the metadata.
Note that the subscriber is free to assign span IDs based on whatever scheme it sees fit. Any guarantees about uniqueness, ordering, or ID reuse are left up to the subscriber implementation to determine.
fn record(self: &Self, span: &Id, values: &Record<'_>)Record a set of values on a span.
This method will be invoked when value is recorded on a span. Recording multiple values for the same field is possible, but the actual behaviour is defined by the subscriber implementation.
Keep in mind that a span might not provide a value for each field it declares.
The subscriber is expected to provide a visitor to the
Record'srecordmethod in order to record the added values.Example
"foo = 3" will be recorded when
recordis called on theAttributespassed tonew_span. Since values are not provided for thebarandbazfields, the span'sMetadatawill indicate that it has those fields, but values for them won't be recorded at this time.# use span; let mut span = span!; // `Subscriber::record` will be called with a `Record` // containing "bar = false" span.record; // `Subscriber::record` will be called with a `Record` // containing "baz = "a string"" span.record;fn record_follows_from(self: &Self, span: &Id, follows: &Id)Adds an indication that
spanfollows from the span with the idfollows.This relationship differs somewhat from the parent-child relationship: a span may have any number of prior spans, rather than a single one; and spans are not considered to be executing inside of the spans they follow from. This means that a span may close even if subsequent spans that follow from it are still open, and time spent inside of a subsequent span should not be included in the time its precedents were executing. This is used to model causal relationships such as when a single future spawns several related background tasks, et cetera.
If the subscriber has spans corresponding to the given IDs, it should record this relationship in whatever way it deems necessary. Otherwise, if one or both of the given span IDs do not correspond to spans that the subscriber knows about, or if a cyclical relationship would be created (i.e., some span a which proceeds some other span b may not also follow from b), it may silently do nothing.
fn event(self: &Self, event: &Event<'_>)Records that an
Eventhas occurred.This method will be invoked when an Event is constructed by the
Event'sdispatchmethod. For example, this happens internally when an event macro fromtracingis called.The key difference between this method and
recordis thatrecordis called when a value is recorded for a field defined by a span, whileeventis called when a new event occurs.The provided
Eventstruct contains any field values attached to the event. The subscriber may pass a visitor to theEvent'srecordmethod to record these values.fn enter(self: &Self, span: &Id)Records that a span has been entered.
When entering a span, this method is called to notify the subscriber that the span has been entered. The subscriber is provided with the span ID of the entered span, and should update any internal state tracking the current span accordingly.
fn exit(self: &Self, span: &Id)Records that a span has been exited.
When exiting a span, this method is called to notify the subscriber that the span has been exited. The subscriber is provided with the span ID of the exited span, and should update any internal state tracking the current span accordingly.
Exiting a span does not imply that the span will not be re-entered.
Provided Methods
fn on_register_dispatch(self: &Self, subscriber: &Dispatch)Invoked when this subscriber becomes a
Dispatch.Avoiding Memory Leaks
Subscribers should not store their ownDispatch. Because theDispatchowns theSubscriber, storing theDispatchwithin theSubscriberwill create a reference count cycle, preventing theDispatchfrom ever being dropped.Instead, when it is necessary to store a cyclical reference to the
Dispatchwithin aSubscriber, useDispatch::downgradeto convert aDispatchinto aWeakDispatch. This type is analogous tostd::sync::Weak, and does not create a reference count cycle. AWeakDispatchcan be stored within aSubscriberwithout causing a memory leak, and can be upgraded into aDispatchtemporarily when theDispatchmust be accessed by theSubscriber.fn register_callsite(self: &Self, metadata: &'static Metadata<'static>) -> InterestRegisters a new callsite with this subscriber, returning whether or not the subscriber is interested in being notified about the callsite.
By default, this function assumes that the subscriber's filter represents an unchanging view of its interest in the callsite. However, if this is not the case, subscribers may override this function to indicate different interests, or to implement behaviour that should run once for every callsite.
This function is guaranteed to be called at least once per callsite on every active subscriber. The subscriber may store the keys to fields it cares about in order to reduce the cost of accessing fields by name, preallocate storage for that callsite, or perform any other actions it wishes to perform once for each callsite.
The subscriber should then return an
Interest, indicating whether it is interested in being notified about that callsite in the future. This may beAlwaysindicating that the subscriber always wishes to be notified about the callsite, and its filter need not be re-evaluated;Sometimes, indicating that the subscriber may sometimes care about the callsite but not always (such as when sampling), orNever, indicating that the subscriber never wishes to be notified about that callsite. If all active subscribers returnNever, a callsite will never be enabled unless a new subscriber expresses interest in it.Subscribers which require their filters to be run every time an event occurs or a span is entered/exited should returnInterest::sometimes. If a subscriber returnsInterest::sometimes, then itsenabledmethod will be called every time an event or span is created from that callsite.For example, suppose a sampling subscriber is implemented by incrementing a counter every time
enabledis called and only returningtruewhen the counter is divisible by a specified sampling rate. If that subscriber returnsInterest::alwaysfromregister_callsite, then the filter will not be re-evaluated once it has been applied to a given set of metadata. Thus, the counter will not be incremented, and the span or event that corresponds to the metadata will never beenabled.Subscribers that need to change their filters occasionally should callrebuild_interest_cacheto re-evaluateregister_callsitefor all callsites.Similarly, if a
Subscriberhas a filtering strategy that can be changed dynamically at runtime, it would need to re-evaluate that filter if the cached results have changed.A subscriber which manages fanout to multiple other subscribers should proxy this decision to all of its child subscribers, returning
Interest::neveronly if all such children returnInterest::never. If the set of subscribers to which spans are broadcast may change dynamically, the subscriber should also never returnInterest::Never, as a new subscriber may be added that is interested.See the documentation on the callsite registry for more details on how and when the
register_callsitemethod is called.Notes
This function may be called again when a new subscriber is created or when the registry is invalidated.
If a subscriber returns
Interest::neverfor a particular callsite, it may still see spans and events originating from that callsite, if another subscriber expressed interest in it.fn max_level_hint(self: &Self) -> Option<LevelFilter>Returns the highest verbosity level that this
Subscriberwill enable, orNone, if the subscriber does not implement level-based filtering or chooses not to implement this method.If this method returns a
Level, it will be used as a hint to determine the most verbose level that will be enabled. This will allow spans and events which are more verbose than that level to be skipped more efficiently. Subscribers which perform filtering are strongly encouraged to provide an implementation of this method.If the maximum level the subscriber will enable can change over the course of its lifetime, it is free to return a different value from multiple invocations of this method. However, note that changes in the maximum level will only be reflected after the callsite
Interestcache is rebuilt, by calling thecallsite::rebuild_interest_cachefunction. Therefore, if the subscriber will change the value returned by this method, it is responsible for ensuring thatrebuild_interest_cacheis called after the value of the max level changes.fn event_enabled(self: &Self, event: &Event<'_>) -> boolDetermine if an
Eventshould be recorded.By default, this returns
trueandSubscribers can filter events in [event][Self::event] without any penalty. However, wheneventis more complicated, this can be used to determine ifeventshould be called at all, separating out the decision from the processing.fn clone_span(self: &Self, id: &Id) -> IdNotifies the subscriber that a span ID has been cloned.
This function is guaranteed to only be called with span IDs that were returned by this subscriber's
new_spanfunction.Note that the default implementation of this function this is just the identity function, passing through the identifier. However, it can be used in conjunction with
try_closeto track the number of handles capable ofentering a span. When all the handles have been dropped (i.e.,try_closehas been called one more time thanclone_spanfor a given ID), the subscriber may assume that the span will not be entered again. It is then free to deallocate storage for data associated with that span, write data from that span to IO, and so on.For more unsafe situations, however, if
idis itself a pointer of some kind this can be used as a hook to "clone" the pointer, depending on what that means for the specified pointer.fn drop_span(self: &Self, _id: Id)This method is deprecated.
Using
drop_spanmay result in subscribers composed usingtracing-subscribercrate'sLayertrait from observing close events. Usetry_closeinstead.The default implementation of this function does nothing.
fn try_close(self: &Self, id: Id) -> boolNotifies the subscriber that a span ID has been dropped, and returns
trueif there are now 0 IDs that refer to that span.Higher-level libraries providing functionality for composing multiple subscriber implementations may use this return value to notify any "layered" subscribers that this subscriber considers the span closed.
The default implementation of this method calls the subscriber's
drop_spanmethod and returnsfalse. This means that, unless the subscriber overrides the default implementation, close notifications will never be sent to any layered subscribers. In general, if the subscriber tracks reference counts, this method should be implemented, rather thandrop_span.This function is guaranteed to only be called with span IDs that were returned by this subscriber's
new_spanfunction.It's guaranteed that if this function has been called once more than the number of times
clone_spanwas called with the sameid, then no more handles that can enter the span with thatidexist. This means that it can be used in conjunction withclone_spanto track the number of handles capable ofentering a span. When all the handles have been dropped (i.e.,try_closehas been called one more time thanclone_spanfor a given ID), the subscriber may assume that the span will not be entered again, and should returntrue. It is then free to deallocate storage for data associated with that span, write data from that span to IO, and so on.Note: since this function is called when spans are dropped, implementations should ensure that they are unwind-safe. Panicking from inside of a
try_closefunction may cause a double panic, if the span was dropped due to a thread unwinding.fn current_span(self: &Self) -> CurrentReturns a type representing this subscriber's view of the current span.
If subscribers track a current span, they should override this function to return
Current::newif the thread from which this method is called is inside a span, orCurrent::noneif the thread is not inside a span.By default, this returns a value indicating that the subscriber does not track what span is current. If the subscriber does not implement a current span, it should not override this method.
unsafe fn downcast_raw(self: &Self, id: TypeId) -> Option<*const ()>If
selfis the same type as the providedTypeId, returns an untyped*constpointer to that type. Otherwise, returnsNone.If you wish to downcast a
Subscriber, it is strongly advised to use the safe API provided bydowncast_refinstead.This API is required for
downcast_rawto be a trait method; a method signature likedowncast_ref(with a generic type parameter) is not object-safe, and thus cannot be a trait method forSubscriber. This means that if we only exposeddowncast_ref,Subscriberimplementations could not override the downcasting behaviorThis method may be overridden by "fan out" or "chained" subscriber implementations which consist of multiple composed types. Such subscribers might allow
downcast_rawby returning references to those component if they contain components with the givenTypeId.Safety
The
downcast_refmethod expects that the pointer returned bydowncast_rawis non-null and points to a valid instance of the type with the providedTypeId. Failure to ensure this will result in undefined behaviour, so implementingdowncast_rawis unsafe.
Implementors
impl<S> Subscriber for Arc<S>impl<S> Subscriber for Box<S>impl Subscriber for NoSubscriber