-
Notifications
You must be signed in to change notification settings - Fork 662
/
subscribe.rs
1519 lines (1390 loc) · 52.6 KB
/
subscribe.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A composable abstraction for building [collector]s.
//!
//! [collector]: tracing_core::Collect
use tracing_core::{
collect::{Collect, Interest},
metadata::Metadata,
span, Event, LevelFilter,
};
#[cfg(all(feature = "std", feature = "registry"))]
use crate::registry::Registry;
use crate::registry::{self, LookupSpan, SpanRef};
use core::{any::TypeId, cmp, marker::PhantomData, ptr::NonNull};
feature! {
#![feature = "alloc"]
use alloc::boxed::Box;
use core::ops::Deref;
}
/// A composable handler for `tracing` events.
///
/// The [`Collect`] trait in `tracing-core` represents the _complete_ set of
/// functionality required to consume `tracing` instrumentation. This means that
/// a single [collector] instance is a self-contained implementation of a
/// complete strategy for collecting traces; but it _also_ means that the
/// `Collect` trait cannot easily be composed with other `Collect`s.
///
/// In particular, collectors are responsible for generating [span IDs] and
/// assigning them to spans. Since these IDs must uniquely identify a span
/// within the context of the current trace, this means that there may only be
/// a single [collector] for a given thread at any point in time —
/// otherwise, there would be no authoritative source of span IDs.
///
/// [collector]: tracing_core::Collect
///
/// On the other hand, the majority of the [`Collect`] trait's functionality
/// is composable: any number of collectors may _observe_ events, span entry
/// and exit, and so on, provided that there is a single authoritative source of
/// span IDs. The `Subscribe` trait represents this composable subset of the
/// [`Collect`]'s behavior; it can _observe_ events and spans, but does not
/// assign IDs.
///
/// ## Composing Subscribers
///
/// Since `Subscribe` does not implement a complete strategy for collecting
/// traces, it must be composed with a `Collect` in order to be used. The
/// `Subscribe` trait is generic over a type parameter (called `C` in the trait
/// definition), representing the types of `Collect` they can be composed
/// with. Thus, a subscriber may be implemented that will only compose with a
/// particular `Collect` implementation, or additional trait bounds may be
/// added to constrain what types implementing `Collect` a subscriber can wrap.
///
/// Subscribers may be added to a `Collect` by using the [`CollectExt::with`]
/// method, which is provided by `tracing-subscriber`'s [prelude]. This method
/// returns a [`Layered`] struct that implements `Collect` by composing the
/// subscriber with the collector.
///
/// For example:
/// ```rust
/// use tracing_subscriber::Subscribe;
/// use tracing_subscriber::subscribe::CollectExt;
/// use tracing::Collect;
/// use tracing_core::span::Current;
///
/// pub struct MySubscriber {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for MySubscriber {
/// // ...
/// }
///
/// pub struct MyCollector {
/// // ...
/// }
///
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// impl Collect for MyCollector {
/// // ...
/// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
/// # fn record(&self, _: &Id, _: &Record) {}
/// # fn event(&self, _: &Event) {}
/// # fn record_follows_from(&self, _: &Id, _: &Id) {}
/// # fn enabled(&self, _: &Metadata) -> bool { false }
/// # fn enter(&self, _: &Id) {}
/// # fn exit(&self, _: &Id) {}
/// # fn current_span(&self) -> Current { Current::unknown() }
/// }
/// # impl MySubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyCollector {
/// # fn new() -> Self { Self { }}
/// # }
///
/// let collector = MyCollector::new()
/// .with(MySubscriber::new());
///
/// tracing::collect::set_global_default(collector);
/// ```
///
/// Multiple `Subscriber`s may be composed in the same manner:
/// ```rust
/// # use tracing_subscriber::Subscribe;
/// # use tracing_subscriber::subscribe::CollectExt;
/// # use tracing::Collect;
/// # use tracing_core::span::Current;
/// pub struct MyOtherSubscriber {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for MyOtherSubscriber {
/// // ...
/// }
///
/// pub struct MyThirdSubscriber {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for MyThirdSubscriber {
/// // ...
/// }
/// # pub struct MySubscriber {}
/// # impl<C: Collect> Subscribe<C> for MySubscriber {}
/// # pub struct MyCollector { }
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// # impl Collect for MyCollector {
/// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
/// # fn record(&self, _: &Id, _: &Record) {}
/// # fn event(&self, _: &Event) {}
/// # fn record_follows_from(&self, _: &Id, _: &Id) {}
/// # fn enabled(&self, _: &Metadata) -> bool { false }
/// # fn enter(&self, _: &Id) {}
/// # fn exit(&self, _: &Id) {}
/// # fn current_span(&self) -> Current { Current::unknown() }
/// }
/// # impl MySubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyOtherSubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyThirdSubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyCollector {
/// # fn new() -> Self { Self { }}
/// # }
///
/// let collector = MyCollector::new()
/// .with(MySubscriber::new())
/// .with(MyOtherSubscriber::new())
/// .with(MyThirdSubscriber::new());
///
/// tracing::collect::set_global_default(collector);
/// ```
///
/// The [`Subscribe::with_collector` method][with-col] constructs the `Layered`
/// type from a `Subscribe` and `Collect`, and is called by
/// [`CollectExt::with`]. In general, it is more idiomatic to use
/// `CollectExt::with`, and treat `Subscribe::with_collector` as an
/// implementation detail, as `with_collector` calls must be nested, leading to
/// less clear code for the reader. However, subscribers which wish to perform
/// additional behavior when composed with a subscriber may provide their own
/// implementations of `SubscriberExt::with`.
///
/// [prelude]: super::prelude
/// [with-col]: Subscribe::with_collector()
///
/// ## Recording Traces
///
/// The `Subscribe` trait defines a set of methods for consuming notifications from
/// tracing instrumentation, which are generally equivalent to the similarly
/// named methods on [`Collect`]. Unlike [`Collect`], the methods on
/// `Subscribe` are additionally passed a [`Context`] type, which exposes additional
/// information provided by the wrapped collector (such as [the current span])
/// to the subscriber.
///
/// ## Filtering with Subscribers
///
/// As well as strategies for handling trace events, the `Subscriber` trait may also
/// be used to represent composable _filters_. This allows the determination of
/// what spans and events should be recorded to be decoupled from _how_ they are
/// recorded: a filtering subscriber can be applied to other subscribers or
/// collectors. A `Subscriber` that implements a filtering strategy should override the
/// [`register_callsite`] and/or [`enabled`] methods. It may also choose to implement
/// methods such as [`on_enter`] or [`event_enabled`], if it wishes to filter events
/// based on the current span context.
///
/// Note that the [`register_callsite`], [`enabled`], and [`event_enabled`] methods
/// determine whether a span or event is enabled *globally*. Thus, they should
/// **not** be used to indicate whether an individual subscriber wishes to record a
/// particular span or event. Instead, if a subscriber is only interested in a subset
/// of trace data, but does *not* wish to disable other spans and events for the
/// rest of the subscriber stack should ignore those spans and events in its
/// notification methods.
///
/// The filtering methods on a stack of subscribers are evaluated in a top-down
/// order, starting with the outermost `Subscribe` and ending with the wrapped
/// [`Collect`]. If any subscriber returns `false` from its [`enabled`] method, or
/// [`Interest::never()`] from its [`register_callsite`] method, filter
/// evaluation will short-circuit and the span or event will be disabled.
///
/// [`Collect`]: tracing_core::collect::Collect
/// [span IDs]: tracing_core::span::Id
/// [the current span]: Context::current_span()
/// [`register_callsite`]: Subscribe::register_callsite()
/// [`enabled`]: Subscribe::enabled()
/// [`on_enter`]: Subscribe::on_enter()
/// [`event_enabled`]: Subscribe::on_enter()
pub trait Subscribe<C>
where
C: Collect,
Self: 'static,
{
/// Registers a new callsite with this subscriber, returning whether or not
/// the subscriber is interested in being notified about the callsite, similarly
/// to [`Collect::register_callsite`].
///
/// By default, this returns [`Interest::always()`] if [`self.enabled`] returns
/// true, or [`Interest::never()`] if it returns false.
///
/// <div class="example-wrap" style="display:inline-block">
/// <pre class="ignore" style="white-space:normal;font:inherit;">
///
/// **Note**: This method (and [`Subscribe::enabled`]) determine whether a span or event is
/// globally enabled, *not* whether the individual subscriber will be notified about that
/// span or event. This is intended to be used by subscribers that implement filtering for
/// the entire stack. Subscribers which do not wish to be notified about certain spans or
/// events but do not wish to globally disable them should ignore those spans or events in
/// their [on_event][Self::on_event], [on_enter][Self::on_enter], [on_exit][Self::on_exit],
/// and other notification methods.
///
/// </pre></div>
///
/// See [the trait-level documentation] for more information on filtering
/// with `Subscriber`s.
///
/// Subscribers may also implement this method to perform any behaviour that
/// should be run once per callsite. If the subscriber wishes to use
/// `register_callsite` for per-callsite behaviour, but does not want to
/// globally enable or disable those callsites, it should always return
/// [`Interest::always()`].
///
/// [`Interest`]: tracing_core::Interest
/// [`Collect::register_callsite`]: tracing_core::Collect::register_callsite()
/// [`self.enabled`]: Subscribe::enabled()
/// [the trait-level documentation]: #filtering-with-subscribers
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
if self.enabled(metadata, Context::none()) {
Interest::always()
} else {
Interest::never()
}
}
/// Returns `true` if this subscriber is interested in a span or event with the
/// given `metadata` in the current [`Context`], similarly to
/// [`Collect::enabled`].
///
/// By default, this always returns `true`, allowing the wrapped collector
/// to choose to disable the span.
///
/// <div class="example-wrap" style="display:inline-block">
/// <pre class="ignore" style="white-space:normal;font:inherit;">
///
/// **Note**: This method (and [`register_callsite`][Self::register_callsite])
/// determine whether a span or event is
/// globally enabled, *not* whether the individual subscriber will be
/// notified about that span or event. This is intended to be used
/// by layers that implement filtering for the entire stack. Layers which do
/// not wish to be notified about certain spans or events but do not wish to
/// globally disable them should ignore those spans or events in their
/// [on_event][Self::on_event], [on_enter][Self::on_enter], [on_exit][Self::on_exit],
/// and other notification methods.
///
/// </pre></div>
///
///
/// See [the trait-level documentation] for more information on filtering
/// with `Subscriber`s.
///
/// [`Interest`]: tracing_core::Interest
/// [the trait-level documentation]: #filtering-with-subscribers
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
let _ = (metadata, ctx);
true
}
/// Notifies this subscriber that a new span was constructed with the given
/// `Attributes` and `Id`.
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
let _ = (attrs, id, ctx);
}
// TODO(eliza): do we want this to be a public API? If we end up moving
// filtering subscribers to a separate trait, we may no longer want `Subscriber`s to
// be able to participate in max level hinting...
#[doc(hidden)]
fn max_level_hint(&self) -> Option<LevelFilter> {
None
}
/// Notifies this subscriber that a span with the given `Id` recorded the given
/// `values`.
// Note: it's unclear to me why we'd need the current span in `record` (the
// only thing the `Context` type currently provides), but passing it in anyway
// seems like a good future-proofing measure as it may grow other methods later...
fn on_record(&self, _span: &span::Id, _values: &span::Record<'_>, _ctx: Context<'_, C>) {}
/// Notifies this subscriber that a span with the ID `span` recorded that it
/// follows from the span with the ID `follows`.
// Note: it's unclear to me why we'd need the current span in `record` (the
// only thing the `Context` type currently provides), but passing it in anyway
// seems like a good future-proofing measure as it may grow other methods later...
fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<'_, C>) {}
/// Called before `on_event`, to determine if `on_event` should be called.
///
/// <div class="example-wrap" style="display:inline-block">
/// <pre class="ignore" style="white-space:normal;font:inherit;">
///
/// **Note**: This method determines whether an event is globally enabled,
/// *not* whether the individual subscriber will be notified about the
/// event. This is intended to be used by layers that implement filtering
/// for the entire stack. Layers which do not wish to be notified about
/// certain events but do not wish to globally disable them should ignore
/// those events in their [on_event][Self::on_event].
///
/// </pre></div>
///
/// See [the trait-level documentation] for more information on filtering
/// with `Subscriber`s.
///
/// [`Interest`]: tracing_core::Interest
/// [the trait-level documentation]: #filtering-with-subscribers
#[inline] // collapse this to a constant please mrs optimizer
fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, C>) -> bool {
true
}
/// Notifies this subscriber that an event has occurred.
fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, C>) {}
/// Notifies this subscriber that a span with the given ID was entered.
fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, C>) {}
/// Notifies this subscriber that the span with the given ID was exited.
fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, C>) {}
/// Notifies this subscriber that the span with the given ID has been closed.
fn on_close(&self, _id: span::Id, _ctx: Context<'_, C>) {}
/// Notifies this subscriber that a span ID has been cloned, and that the
/// subscriber returned a different ID.
fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<'_, C>) {}
/// Composes this subscriber around the given collector, returning a `Layered`
/// struct implementing `Subscribe`.
///
/// The returned subscriber will call the methods on this subscriber and then
/// those of the new subscriber, before calling the methods on the collector
/// it wraps. For example:
///
/// ```rust
/// # use tracing_subscriber::subscribe::Subscribe;
/// # use tracing_core::Collect;
/// # use tracing_core::span::Current;
/// pub struct FooSubscriber {
/// // ...
/// }
///
/// pub struct BarSubscriber {
/// // ...
/// }
///
/// pub struct MyCollector {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for FooSubscriber {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for BarSubscriber {
/// // ...
/// }
///
/// # impl FooSubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl BarSubscriber {
/// # fn new() -> Self { Self { }}
/// # }
/// # impl MyCollector {
/// # fn new() -> Self { Self { }}
/// # }
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// # impl tracing_core::Collect for MyCollector {
/// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
/// # fn record(&self, _: &Id, _: &Record) {}
/// # fn event(&self, _: &Event) {}
/// # fn record_follows_from(&self, _: &Id, _: &Id) {}
/// # fn enabled(&self, _: &Metadata) -> bool { false }
/// # fn enter(&self, _: &Id) {}
/// # fn exit(&self, _: &Id) {}
/// # fn current_span(&self) -> Current { Current::unknown() }
/// # }
/// let collector = FooSubscriber::new()
/// .and_then(BarSubscriber::new())
/// .with_collector(MyCollector::new());
/// ```
///
/// Multiple subscribers may be composed in this manner:
///
/// ```rust
/// # use tracing_subscriber::subscribe::Subscribe;
/// # use tracing_core::{Collect, span::Current};
/// # pub struct FooSubscriber {}
/// # pub struct BarSubscriber {}
/// # pub struct MyCollector {}
/// # impl<C: Collect> Subscribe<C> for FooSubscriber {}
/// # impl<C: Collect> Subscribe<C> for BarSubscriber {}
/// # impl FooSubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl BarSubscriber {
/// # fn new() -> Self { Self { }}
/// # }
/// # impl MyCollector {
/// # fn new() -> Self { Self { }}
/// # }
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// # impl tracing_core::Collect for MyCollector {
/// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
/// # fn record(&self, _: &Id, _: &Record) {}
/// # fn event(&self, _: &Event) {}
/// # fn record_follows_from(&self, _: &Id, _: &Id) {}
/// # fn enabled(&self, _: &Metadata) -> bool { false }
/// # fn enter(&self, _: &Id) {}
/// # fn exit(&self, _: &Id) {}
/// # fn current_span(&self) -> Current { Current::unknown() }
/// # }
/// pub struct BazSubscriber {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for BazSubscriber {
/// // ...
/// }
/// # impl BazSubscriber { fn new() -> Self { BazSubscriber {} } }
///
/// let collector = FooSubscriber::new()
/// .and_then(BarSubscriber::new())
/// .and_then(BazSubscriber::new())
/// .with_collector(MyCollector::new());
/// ```
fn and_then<S>(self, subscriber: S) -> Layered<S, Self, C>
where
S: Subscribe<C>,
Self: Sized,
{
Layered {
subscriber,
inner: self,
_s: PhantomData,
}
}
/// Composes this subscriber with the given collector, returning a
/// `Layered` struct that implements [`Collect`].
///
/// The returned `Layered` subscriber will call the methods on this subscriber
/// and then those of the wrapped collector.
///
/// For example:
/// ```rust
/// # use tracing_subscriber::subscribe::Subscribe;
/// # use tracing_core::Collect;
/// # use tracing_core::span::Current;
/// pub struct FooSubscriber {
/// // ...
/// }
///
/// pub struct MyCollector {
/// // ...
/// }
///
/// impl<C: Collect> Subscribe<C> for FooSubscriber {
/// // ...
/// }
///
/// # impl FooSubscriber {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyCollector {
/// # fn new() -> Self { Self { }}
/// # }
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
/// # impl tracing_core::Collect for MyCollector {
/// # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
/// # fn record(&self, _: &Id, _: &Record) {}
/// # fn event(&self, _: &tracing_core::Event) {}
/// # fn record_follows_from(&self, _: &Id, _: &Id) {}
/// # fn enabled(&self, _: &Metadata) -> bool { false }
/// # fn enter(&self, _: &Id) {}
/// # fn exit(&self, _: &Id) {}
/// # fn current_span(&self) -> Current { Current::unknown() }
/// # }
/// let collector = FooSubscriber::new()
/// .with_collector(MyCollector::new());
///```
///
/// [`Collect`]: tracing_core::Collect
fn with_collector(self, inner: C) -> Layered<Self, C>
where
Self: Sized,
{
Layered {
subscriber: self,
inner,
_s: PhantomData,
}
}
#[doc(hidden)]
unsafe fn downcast_raw(&self, id: TypeId) -> Option<NonNull<()>> {
if id == TypeId::of::<Self>() {
Some(NonNull::from(self).cast())
} else {
None
}
}
}
/// Extension trait adding a `with(Subscriber)` combinator to `Collect`.
pub trait CollectExt: Collect + crate::sealed::Sealed {
/// Wraps `self` with the provided `subscriber`.
fn with<S>(self, subscriber: S) -> Layered<S, Self>
where
S: Subscribe<Self>,
Self: Sized,
{
subscriber.with_collector(self)
}
}
/// Represents information about the current context provided to [subscriber]s by the
/// wrapped [collector].
///
/// To access [stored data] keyed by a span ID, implementors of the `Subscribe`
/// trait should ensure that the `Collect` type parameter is *also* bound by the
/// [`LookupSpan`]:
///
/// ```rust
/// use tracing::Collect;
/// use tracing_subscriber::{Subscribe, registry::LookupSpan};
///
/// pub struct MyCollector;
///
/// impl<C> Subscribe<C> for MyCollector
/// where
/// C: Collect + for<'a> LookupSpan<'a>,
/// {
/// // ...
/// }
/// ```
///
/// [subscriber]: Subscribe
/// [collector]: tracing_core::Collect
/// [stored data]: super::registry::SpanRef
#[derive(Debug)]
pub struct Context<'a, C> {
collector: Option<&'a C>,
}
/// A [collector] composed of a collector wrapped by one or more
/// [subscriber]s.
///
/// [subscriber]: super::subscribe::Subscribe
/// [collector]: tracing_core::Collect
#[derive(Clone, Debug)]
pub struct Layered<S, I, C = I> {
subscriber: S,
inner: I,
_s: PhantomData<fn(C)>,
}
/// A Subscriber that does nothing.
#[derive(Clone, Debug, Default)]
pub struct Identity {
_p: (),
}
// === impl Layered ===
impl<S, C> Collect for Layered<S, C>
where
S: Subscribe<C>,
C: Collect,
{
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
let outer = self.subscriber.register_callsite(metadata);
if outer.is_never() {
// if the outer subscriber has disabled the callsite, return now so that
// the collector doesn't get its hopes up.
return outer;
}
// The intention behind calling `inner.register_callsite()` before the if statement
// is to ensure that the inner subscriber is informed that the callsite exists
// regardless of the outer subscriber's filtering decision.
let inner = self.inner.register_callsite(metadata);
if outer.is_sometimes() {
// if this interest is "sometimes", return "sometimes" to ensure that
// filters are reevaluated.
outer
} else {
// otherwise, allow the inner subscriber or collector to weigh in.
inner
}
}
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
if self.subscriber.enabled(metadata, self.ctx()) {
// if the outer subscriber enables the callsite metadata, ask the collector.
self.inner.enabled(metadata)
} else {
// otherwise, the callsite is disabled by the subscriber
false
}
}
fn max_level_hint(&self) -> Option<LevelFilter> {
cmp::max(
self.subscriber.max_level_hint(),
self.inner.max_level_hint(),
)
}
fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
let id = self.inner.new_span(span);
self.subscriber.on_new_span(span, &id, self.ctx());
id
}
fn record(&self, span: &span::Id, values: &span::Record<'_>) {
self.inner.record(span, values);
self.subscriber.on_record(span, values, self.ctx());
}
fn record_follows_from(&self, span: &span::Id, follows: &span::Id) {
self.inner.record_follows_from(span, follows);
self.subscriber.on_follows_from(span, follows, self.ctx());
}
fn event(&self, event: &Event<'_>) {
if self.subscriber.event_enabled(event, self.ctx()) {
self.inner.event(event);
self.subscriber.on_event(event, self.ctx());
}
}
fn enter(&self, span: &span::Id) {
self.inner.enter(span);
self.subscriber.on_enter(span, self.ctx());
}
fn exit(&self, span: &span::Id) {
self.inner.exit(span);
self.subscriber.on_exit(span, self.ctx());
}
fn clone_span(&self, old: &span::Id) -> span::Id {
let new = self.inner.clone_span(old);
if &new != old {
self.subscriber.on_id_change(old, &new, self.ctx())
};
new
}
#[inline]
fn drop_span(&self, id: span::Id) {
self.try_close(id);
}
fn try_close(&self, id: span::Id) -> bool {
#[cfg(all(feature = "registry", feature = "std"))]
let subscriber = &self.inner as &dyn Collect;
#[cfg(all(feature = "registry", feature = "std"))]
let mut guard = subscriber
.downcast_ref::<Registry>()
.map(|registry| registry.start_close(id.clone()));
if self.inner.try_close(id.clone()) {
// If we have a registry's close guard, indicate that the span is
// closing.
#[cfg(all(feature = "registry", feature = "std"))]
{
if let Some(g) = guard.as_mut() {
g.is_closing()
};
}
self.subscriber.on_close(id, self.ctx());
true
} else {
false
}
}
#[inline]
fn current_span(&self) -> span::Current {
self.inner.current_span()
}
#[doc(hidden)]
unsafe fn downcast_raw(&self, id: TypeId) -> Option<NonNull<()>> {
if id == TypeId::of::<Self>() {
return Some(NonNull::from(self).cast());
}
self.subscriber
.downcast_raw(id)
.or_else(|| self.inner.downcast_raw(id))
}
}
impl<C, A, B> Subscribe<C> for Layered<A, B, C>
where
A: Subscribe<C>,
B: Subscribe<C>,
C: Collect,
{
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
let outer = self.subscriber.register_callsite(metadata);
if outer.is_never() {
// if the outer subscriber has disabled the callsite, return now so that
// inner subscribers don't get their hopes up.
return outer;
}
// The intention behind calling `inner.register_callsite()` before the if statement
// is to ensure that the inner subscriber is informed that the callsite exists
// regardless of the outer subscriber's filtering decision.
let inner = self.inner.register_callsite(metadata);
if outer.is_sometimes() {
// if this interest is "sometimes", return "sometimes" to ensure that
// filters are reevaluated.
outer
} else {
// otherwise, allow the inner subscriber or collector to weigh in.
inner
}
}
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
if self.subscriber.enabled(metadata, ctx.clone()) {
// if the outer subscriber enables the callsite metadata, ask the inner subscriber.
self.inner.enabled(metadata, ctx)
} else {
// otherwise, the callsite is disabled by this subscriber
false
}
}
#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
self.inner.on_new_span(attrs, id, ctx.clone());
self.subscriber.on_new_span(attrs, id, ctx);
}
#[inline]
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, C>) {
self.inner.on_record(span, values, ctx.clone());
self.subscriber.on_record(span, values, ctx);
}
#[inline]
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, C>) {
self.inner.on_follows_from(span, follows, ctx.clone());
self.subscriber.on_follows_from(span, follows, ctx);
}
#[inline]
fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, C>) -> bool {
if self.subscriber.event_enabled(event, ctx.clone()) {
// if the outer subscriber enables the callsite metadata, ask the inner subscriber.
self.inner.event_enabled(event, ctx)
} else {
// otherwise, the callsite is disabled by this subscriber
false
}
}
#[inline]
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, C>) {
self.inner.on_event(event, ctx.clone());
self.subscriber.on_event(event, ctx);
}
#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, C>) {
self.inner.on_enter(id, ctx.clone());
self.subscriber.on_enter(id, ctx);
}
#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, C>) {
self.inner.on_exit(id, ctx.clone());
self.subscriber.on_exit(id, ctx);
}
#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, C>) {
self.inner.on_close(id.clone(), ctx.clone());
self.subscriber.on_close(id, ctx);
}
#[inline]
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, C>) {
self.inner.on_id_change(old, new, ctx.clone());
self.subscriber.on_id_change(old, new, ctx);
}
#[doc(hidden)]
unsafe fn downcast_raw(&self, id: TypeId) -> Option<NonNull<()>> {
if id == TypeId::of::<Self>() {
return Some(NonNull::from(self).cast());
}
self.subscriber
.downcast_raw(id)
.or_else(|| self.inner.downcast_raw(id))
}
}
impl<S, C> Subscribe<C> for Option<S>
where
S: Subscribe<C>,
C: Collect,
{
#[inline]
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
match self {
Some(ref inner) => inner.register_callsite(metadata),
None => Interest::always(),
}
}
#[inline]
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
match self {
Some(ref inner) => inner.enabled(metadata, ctx),
None => true,
}
}
#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_new_span(attrs, id, ctx)
}
}
#[inline]
fn max_level_hint(&self) -> Option<LevelFilter> {
match self {
Some(ref inner) => inner.max_level_hint(),
None => None,
}
}
#[inline]
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_record(span, values, ctx);
}
}
#[inline]
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_follows_from(span, follows, ctx);
}
}
#[inline]
fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, C>) -> bool {
match self {
Some(ref inner) => inner.event_enabled(event, ctx),
None => true,
}
}
#[inline]
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_event(event, ctx);
}
}
#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_enter(id, ctx);
}
}
#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_exit(id, ctx);
}
}
#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_close(id, ctx);
}
}
#[inline]
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, C>) {
if let Some(ref inner) = self {
inner.on_id_change(old, new, ctx)
}
}
#[doc(hidden)]
#[inline]
unsafe fn downcast_raw(&self, id: TypeId) -> Option<NonNull<()>> {
if id == TypeId::of::<Self>() {
Some(NonNull::from(self).cast())
} else {
self.as_ref().and_then(|inner| inner.downcast_raw(id))
}
}
}
feature! {
#![any(feature = "std", feature = "alloc")]
macro_rules! subscriber_impl_body {
() => {
#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, C>) {
self.deref().on_new_span(attrs, id, ctx)
}
#[inline]
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
self.deref().register_callsite(metadata)
}
#[inline]
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, C>) -> bool {
self.deref().enabled(metadata, ctx)
}
#[inline]
fn max_level_hint(&self) -> Option<LevelFilter> {
self.deref().max_level_hint()
}
#[inline]
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, C>) {
self.deref().on_record(span, values, ctx)
}
#[inline]
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, C>) {
self.deref().on_follows_from(span, follows, ctx)
}
#[inline]
fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, C>) -> bool {
self.deref().event_enabled(event, ctx)
}
#[inline]
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, C>) {
self.deref().on_event(event, ctx)
}
#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, C>) {
self.deref().on_enter(id, ctx)
}
#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, C>) {
self.deref().on_exit(id, ctx)
}
#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, C>) {
self.deref().on_close(id, ctx)
}
#[inline]