logo
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
//! A composable abstraction for building `Subscriber`s.
use tracing_core::{
    metadata::Metadata,
    span,
    subscriber::{Interest, Subscriber},
    Event, LevelFilter,
};

#[cfg(feature = "registry")]
use crate::registry::{self, LookupSpan, Registry, SpanRef};
use std::{any::TypeId, marker::PhantomData};

/// A composable handler for `tracing` events.
///
/// The [`Subscriber`] trait in `tracing-core` represents the _complete_ set of
/// functionality required to consume `tracing` instrumentation. This means that
/// a single `Subscriber` instance is a self-contained implementation of a
/// complete strategy for collecting traces; but it _also_ means that the
/// `Subscriber` trait cannot easily be composed with other `Subscriber`s.
///
/// In particular, [`Subscriber`]'s 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 `Subscriber` for a given thread at any point in time —
/// otherwise, there would be no authoritative source of span IDs.
///
/// On the other hand, the majority of the [`Subscriber`] trait's functionality
/// is composable: any number of subscribers may _observe_ events, span entry
/// and exit, and so on, provided that there is a single authoritative source of
/// span IDs. The `Layer` trait represents this composable subset of the
/// [`Subscriber`] behavior; it can _observe_ events and spans, but does not
/// assign IDs.
///
/// ## Composing Layers
///
/// Since a `Layer` does not implement a complete strategy for collecting
/// traces, it must be composed with a `Subscriber` in order to be used. The
/// `Layer` trait is generic over a type parameter (called `S` in the trait
/// definition), representing the types of `Subscriber` they can be composed
/// with. Thus, a `Layer` may be implemented that will only compose with a
/// particular `Subscriber` implementation, or additional trait bounds may be
/// added to constrain what types implementing `Subscriber` a `Layer` can wrap.
///
/// `Layer`s may be added to a `Subscriber` by using the [`SubscriberExt::with`]
/// method, which is provided by `tracing-subscriber`'s [prelude]. This method
/// returns a [`Layered`] struct that implements `Subscriber` by composing the
/// `Layer` with the `Subscriber`.
///
/// For example:
/// ```rust
/// use tracing_subscriber::Layer;
/// use tracing_subscriber::prelude::*;
/// use tracing::Subscriber;
///
/// pub struct MyLayer {
///     // ...
/// }
///
/// impl<S: Subscriber> Layer<S> for MyLayer {
///     // ...
/// }
///
/// pub struct MySubscriber {
///     // ...
/// }
///
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// impl Subscriber for MySubscriber {
///     // ...
/// #   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) {}
/// }
/// # impl MyLayer {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MySubscriber {
/// # fn new() -> Self { Self { }}
/// # }
///
/// let subscriber = MySubscriber::new()
///     .with(MyLayer::new());
///
/// tracing::subscriber::set_global_default(subscriber);
/// ```
///
/// Multiple `Layer`s may be composed in the same manner:
/// ```rust
/// # use tracing_subscriber::{Layer, layer::SubscriberExt};
/// # use tracing::Subscriber;
/// pub struct MyOtherLayer {
///     // ...
/// }
///
/// impl<S: Subscriber> Layer<S> for MyOtherLayer {
///     // ...
/// }
///
/// pub struct MyThirdLayer {
///     // ...
/// }
///
/// impl<S: Subscriber> Layer<S> for MyThirdLayer {
///     // ...
/// }
/// # pub struct MyLayer {}
/// # impl<S: Subscriber> Layer<S> for MyLayer {}
/// # pub struct MySubscriber { }
/// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
/// # impl Subscriber for MySubscriber {
/// #   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) {}
/// }
/// # impl MyLayer {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyOtherLayer {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MyThirdLayer {
/// # fn new() -> Self { Self {} }
/// # }
/// # impl MySubscriber {
/// # fn new() -> Self { Self { }}
/// # }
///
/// let subscriber = MySubscriber::new()
///     .with(MyLayer::new())
///     .with(MyOtherLayer::new())
///     .with(MyThirdLayer::new());
///
/// tracing::subscriber::set_global_default(subscriber);
/// ```
///
/// The [`Layer::with_subscriber` method][with-sub] constructs the `Layered`
/// type from a `Layer` and `Subscriber`, and is called by
/// [`SubscriberExt::with`]. In general, it is more idiomatic to use
/// `SubscriberExt::with`, and treat `Layer::with_subscriber` as an
/// implementation detail, as `with_subscriber` calls must be nested, leading to
/// less clear code for the reader. However, `Layer`s which wish to perform
/// additional behavior when composed with a subscriber may provide their own
/// implementations of `SubscriberExt::with`.
///
/// [`SubscriberExt::with`]: trait.SubscriberExt.html#method.with
/// [`Layered`]: struct.Layered.html
/// [prelude]: ../prelude/index.html
/// [with-sub]: #method.with_subscriber
///
/// ## Recording Traces
///
/// The `Layer` trait defines a set of methods for consuming notifications from
/// tracing instrumentation, which are generally equivalent to the similarly
/// named methods on [`Subscriber`]. Unlike [`Subscriber`], the methods on
/// `Layer` are additionally passed a [`Context`] type, which exposes additional
/// information provided by the wrapped subscriber (such as [the current span])
/// to the layer.
///
/// ## Filtering with `Layer`s
///
/// As well as strategies for handling trace events, the `Layer` 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 layer can be applied to other layers or
/// subscribers. A `Layer` 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`], if it wishes to filter trace events based on
/// the current span context.
///
/// Note that the [`Layer::register_callsite`] and [`Layer::enabled`] methods
/// determine whether a span or event is enabled *globally*. Thus, they should
/// **not** be used to indicate whether an individual layer wishes to record a
/// particular span or event. Instead, if a layer is only interested in a subset
/// of trace data, but does *not* wish to disable other spans and events for the
/// rest of the layer stack should ignore those spans and events in its
/// notification methods.
///
/// The filtering methods on a stack of `Layer`s are evaluated in a top-down
/// order, starting with the outermost `Layer` and ending with the wrapped
/// [`Subscriber`]. If any layer 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.
///
/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html
/// [span IDs]: https://docs.rs/tracing-core/latest/tracing_core/span/struct.Id.html
/// [`Context`]: struct.Context.html
/// [the current span]: struct.Context.html#method.current_span
/// [`register_callsite`]: #method.register_callsite
/// [`enabled`]: #method.enabled
/// [`on_enter`]: #method.on_enter
/// [`Layer::register_callsite`]: #method.register_callsite
/// [`Layer::enabled`]: #method.enabled
/// [`Interest::never()`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/struct.Interest.html#method.never
pub trait Layer<S>
where
    S: Subscriber,
    Self: 'static,
{
    /// Registers a new callsite with this layer, returning whether or not
    /// the layer is interested in being notified about the callsite, similarly
    /// to [`Subscriber::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;">
    /// <strong>Note</strong>: This method (and <a href="#method.enabled">
    /// <code>Layer::enabled</code></a>) determine whether a span or event is
    /// globally enabled, <em>not</em> whether the individual layer 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
    /// <a href="#method.on_event"><code>on_event</code></a>,
    /// <a href="#method.on_enter"><code>on_enter</code></a>,
    /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
    /// methods.
    /// </pre></div>
    ///
    /// See [the trait-level documentation] for more information on filtering
    /// with `Layer`s.
    ///
    /// Layers may also implement this method to perform any behaviour that
    /// should be run once per callsite. If the layer 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`]: https://docs.rs/tracing-core/latest/tracing_core/struct.Interest.html
    /// [`Subscriber::register_callsite`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html#method.register_callsite
    /// [`Interest::never()`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/struct.Interest.html#method.never
    /// [`Interest::always()`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/struct.Interest.html#method.always
    /// [`self.enabled`]: #method.enabled
    /// [`Layer::enabled`]: #method.enabled
    /// [`on_event`]: #method.on_event
    /// [`on_enter`]: #method.on_enter
    /// [`on_exit`]: #method.on_exit
    /// [the trait-level documentation]: #filtering-with-layers
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        if self.enabled(metadata, Context::none()) {
            Interest::always()
        } else {
            Interest::never()
        }
    }

    /// Returns `true` if this layer is interested in a span or event with the
    /// given `metadata` in the current [`Context`], similarly to
    /// [`Subscriber::enabled`].
    ///
    /// By default, this always returns `true`, allowing the wrapped subscriber
    /// to choose to disable the span.
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This method (and <a href="#method.register_callsite">
    /// <code>Layer::register_callsite</code></a>) determine whether a span or event is
    /// globally enabled, <em>not</em> whether the individual layer 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
    /// <a href="#method.on_event"><code>on_event</code></a>,
    /// <a href="#method.on_enter"><code>on_enter</code></a>,
    /// <a href="#method.on_exit"><code>on_exit</code></a>, and other notification
    /// methods.
    /// </pre></div>
    ///
    ///
    /// See [the trait-level documentation] for more information on filtering
    /// with `Layer`s.
    ///
    /// [`Interest`]: https://docs.rs/tracing-core/latest/tracing_core/struct.Interest.html
    /// [`Context`]: ../struct.Context.html
    /// [`Subscriber::enabled`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html#method.enabled
    /// [`Layer::register_callsite`]: #method.register_callsite
    /// [`on_event`]: #method.on_event
    /// [`on_enter`]: #method.on_enter
    /// [`on_exit`]: #method.on_exit
    /// [the trait-level documentation]: #filtering-with-layers
    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
        let _ = (metadata, ctx);
        true
    }

    /// Notifies this layer that a new span was constructed with the given
    /// `Attributes` and `Id`.
    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
        let _ = (attrs, id, ctx);
    }

    // TODO(eliza): do we want this to be a public API? If we end up moving
    // filtering layers to a separate trait, we may no longer want `Layer`s to
    // be able to participate in max level hinting...
    #[doc(hidden)]
    fn max_level_hint(&self) -> Option<LevelFilter> {
        None
    }

    /// Notifies this layer 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<'_, S>) {}

    /// Notifies this layer 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<'_, S>) {}

    /// Notifies this layer that an event has occurred.
    fn on_event(&self, _event: &Event<'_>, _ctx: Context<'_, S>) {}

    /// Notifies this layer that a span with the given ID was entered.
    fn on_enter(&self, _id: &span::Id, _ctx: Context<'_, S>) {}

    /// Notifies this layer that the span with the given ID was exited.
    fn on_exit(&self, _id: &span::Id, _ctx: Context<'_, S>) {}

    /// Notifies this layer that the span with the given ID has been closed.
    fn on_close(&self, _id: span::Id, _ctx: Context<'_, S>) {}

    /// Notifies this layer 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<'_, S>) {}

    /// Composes this layer around the given `Layer`, returning a `Layered`
    /// struct implementing `Layer`.
    ///
    /// The returned `Layer` will call the methods on this `Layer` and then
    /// those of the new `Layer`, before calling the methods on the subscriber
    /// it wraps. For example:
    ///
    /// ```rust
    /// # use tracing_subscriber::layer::Layer;
    /// # use tracing_core::Subscriber;
    /// pub struct FooLayer {
    ///     // ...
    /// }
    ///
    /// pub struct BarLayer {
    ///     // ...
    /// }
    ///
    /// pub struct MySubscriber {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for FooLayer {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for BarLayer {
    ///     // ...
    /// }
    ///
    /// # impl FooLayer {
    /// # fn new() -> Self { Self {} }
    /// # }
    /// # impl BarLayer {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # impl MySubscriber {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
    /// # impl tracing_core::Subscriber for MySubscriber {
    /// #   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) {}
    /// # }
    /// let subscriber = FooLayer::new()
    ///     .and_then(BarLayer::new())
    ///     .with_subscriber(MySubscriber::new());
    /// ```
    ///
    /// Multiple layers may be composed in this manner:
    ///
    /// ```rust
    /// # use tracing_subscriber::layer::Layer;
    /// # use tracing_core::Subscriber;
    /// # pub struct FooLayer {}
    /// # pub struct BarLayer {}
    /// # pub struct MySubscriber {}
    /// # impl<S: Subscriber> Layer<S> for FooLayer {}
    /// # impl<S: Subscriber> Layer<S> for BarLayer {}
    /// # impl FooLayer {
    /// # fn new() -> Self { Self {} }
    /// # }
    /// # impl BarLayer {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # impl MySubscriber {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
    /// # impl tracing_core::Subscriber for MySubscriber {
    /// #   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) {}
    /// # }
    /// pub struct BazLayer {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for BazLayer {
    ///     // ...
    /// }
    /// # impl BazLayer { fn new() -> Self { BazLayer {} } }
    ///
    /// let subscriber = FooLayer::new()
    ///     .and_then(BarLayer::new())
    ///     .and_then(BazLayer::new())
    ///     .with_subscriber(MySubscriber::new());
    /// ```
    fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
    where
        L: Layer<S>,
        Self: Sized,
    {
        Layered {
            layer,
            inner: self,
            _s: PhantomData,
        }
    }

    /// Composes this `Layer` with the given [`Subscriber`], returning a
    /// `Layered` struct that implements [`Subscriber`].
    ///
    /// The returned `Layered` subscriber will call the methods on this `Layer`
    /// and then those of the wrapped subscriber.
    ///
    /// For example:
    /// ```rust
    /// # use tracing_subscriber::layer::Layer;
    /// # use tracing_core::Subscriber;
    /// pub struct FooLayer {
    ///     // ...
    /// }
    ///
    /// pub struct MySubscriber {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for FooLayer {
    ///     // ...
    /// }
    ///
    /// # impl FooLayer {
    /// # fn new() -> Self { Self {} }
    /// # }
    /// # impl MySubscriber {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
    /// # impl tracing_core::Subscriber for MySubscriber {
    /// #   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) {}
    /// # }
    /// let subscriber = FooLayer::new()
    ///     .with_subscriber(MySubscriber::new());
    ///```
    ///
    /// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
    fn with_subscriber(self, inner: S) -> Layered<Self, S>
    where
        Self: Sized,
    {
        Layered {
            layer: self,
            inner,
            _s: PhantomData,
        }
    }

    #[doc(hidden)]
    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
        if id == TypeId::of::<Self>() {
            Some(self as *const _ as *const ())
        } else {
            None
        }
    }
}

/// Extension trait adding a `with(Layer)` combinator to `Subscriber`s.
pub trait SubscriberExt: Subscriber + crate::sealed::Sealed {
    /// Wraps `self` with the provided `layer`.
    fn with<L>(self, layer: L) -> Layered<L, Self>
    where
        L: Layer<Self>,
        Self: Sized,
    {
        layer.with_subscriber(self)
    }
}

/// Represents information about the current context provided to [`Layer`]s by the
/// wrapped [`Subscriber`].
///
/// To access [stored data] keyed by a span ID, implementors of the `Layer`
/// trait should ensure that the `Subscriber` type parameter is *also* bound by the
/// [`LookupSpan`]:
///
/// ```rust
/// use tracing::Subscriber;
/// use tracing_subscriber::{Layer, registry::LookupSpan};
///
/// pub struct MyLayer;
///
/// impl<S> Layer<S> for MyLayer
/// where
///     S: Subscriber + for<'a> LookupSpan<'a>,
/// {
///     // ...
/// }
/// ```
///
/// [`Layer`]: ../layer/trait.Layer.html
/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
/// [stored data]: ../registry/struct.SpanRef.html
/// [`LookupSpan`]: "../registry/trait.LookupSpan.html
#[derive(Debug)]
pub struct Context<'a, S> {
    subscriber: Option<&'a S>,
}

/// A [`Subscriber`] composed of a `Subscriber` wrapped by one or more
/// [`Layer`]s.
///
/// [`Layer`]: ../layer/trait.Layer.html
/// [`Subscriber`]: https://docs.rs/tracing-core/latest/tracing_core/trait.Subscriber.html
#[derive(Clone, Debug)]
pub struct Layered<L, I, S = I> {
    layer: L,
    inner: I,
    _s: PhantomData<fn(S)>,
}

/// A layer that does nothing.
#[derive(Clone, Debug, Default)]
pub struct Identity {
    _p: (),
}

/// An iterator over the [stored data] for all the spans in the
/// current context, starting the root of the trace tree and ending with
/// the current span.
///
/// This is returned by [`Context::scope`].
///
/// [stored data]: ../registry/struct.SpanRef.html
/// [`Context::scope`]: struct.Context.html#method.scope
#[cfg(feature = "registry")]
#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
#[deprecated(note = "renamed to crate::registry::ScopeFromRoot", since = "0.2.19")]
#[derive(Debug)]
pub struct Scope<'a, L>(std::iter::Flatten<std::option::IntoIter<registry::ScopeFromRoot<'a, L>>>)
where
    L: LookupSpan<'a>;

#[cfg(feature = "registry")]
#[allow(deprecated)]
impl<'a, L> Iterator for Scope<'a, L>
where
    L: LookupSpan<'a>,
{
    type Item = SpanRef<'a, L>;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

// === impl Layered ===

impl<L, S> Subscriber for Layered<L, S>
where
    L: Layer<S>,
    S: Subscriber,
{
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        let outer = self.layer.register_callsite(metadata);
        if outer.is_never() {
            // if the outer layer has disabled the callsite, return now so that
            // the subscriber doesn't get its hopes up.
            return outer;
        }

        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 to weigh in.
            inner
        }
    }

    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
        if self.layer.enabled(metadata, self.ctx()) {
            // if the outer layer enables the callsite metadata, ask the subscriber.
            self.inner.enabled(metadata)
        } else {
            // otherwise, the callsite is disabled by the layer
            false
        }
    }

    fn max_level_hint(&self) -> Option<LevelFilter> {
        std::cmp::max(self.layer.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.layer.new_span(span, &id, self.ctx());
        id
    }

    fn record(&self, span: &span::Id, values: &span::Record<'_>) {
        self.inner.record(span, values);
        self.layer.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.layer.on_follows_from(span, follows, self.ctx());
    }

    fn event(&self, event: &Event<'_>) {
        self.inner.event(event);
        self.layer.on_event(event, self.ctx());
    }

    fn enter(&self, span: &span::Id) {
        self.inner.enter(span);
        self.layer.on_enter(span, self.ctx());
    }

    fn exit(&self, span: &span::Id) {
        self.inner.exit(span);
        self.layer.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.layer.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(feature = "registry")]
        let subscriber = &self.inner as &dyn Subscriber;
        #[cfg(feature = "registry")]
        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(feature = "registry")]
            {
                if let Some(g) = guard.as_mut() {
                    g.is_closing()
                };
            }

            self.layer.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<*const ()> {
        if id == TypeId::of::<Self>() {
            return Some(self as *const _ as *const ());
        }
        self.layer
            .downcast_raw(id)
            .or_else(|| self.inner.downcast_raw(id))
    }
}

impl<S, A, B> Layer<S> for Layered<A, B, S>
where
    A: Layer<S>,
    B: Layer<S>,
    S: Subscriber,
{
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        let outer = self.layer.register_callsite(metadata);
        if outer.is_never() {
            // if the outer layer has disabled the callsite, return now so that
            // inner layers 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 layer to weigh in.
            inner
        }
    }

    fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
        if self.layer.enabled(metadata, ctx.clone()) {
            // if the outer layer enables the callsite metadata, ask the inner layer.
            self.inner.enabled(metadata, ctx)
        } else {
            // otherwise, the callsite is disabled by this layer
            false
        }
    }

    #[inline]
    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
        self.inner.new_span(attrs, id, ctx.clone());
        self.layer.new_span(attrs, id, ctx);
    }

    #[inline]
    fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
        self.inner.on_record(span, values, ctx.clone());
        self.layer.on_record(span, values, ctx);
    }

    #[inline]
    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
        self.inner.on_follows_from(span, follows, ctx.clone());
        self.layer.on_follows_from(span, follows, ctx);
    }

    #[inline]
    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        self.inner.on_event(event, ctx.clone());
        self.layer.on_event(event, ctx);
    }

    #[inline]
    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
        self.inner.on_enter(id, ctx.clone());
        self.layer.on_enter(id, ctx);
    }

    #[inline]
    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
        self.inner.on_exit(id, ctx.clone());
        self.layer.on_exit(id, ctx);
    }

    #[inline]
    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
        self.inner.on_close(id.clone(), ctx.clone());
        self.layer.on_close(id, ctx);
    }

    #[inline]
    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
        self.inner.on_id_change(old, new, ctx.clone());
        self.layer.on_id_change(old, new, ctx);
    }

    #[doc(hidden)]
    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
        if id == TypeId::of::<Self>() {
            return Some(self as *const _ as *const ());
        }
        self.layer
            .downcast_raw(id)
            .or_else(|| self.inner.downcast_raw(id))
    }
}

impl<L, S> Layer<S> for Option<L>
where
    L: Layer<S>,
    S: Subscriber,
{
    #[inline]
    fn new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
        if let Some(ref inner) = self {
            inner.new_span(attrs, id, ctx)
        }
    }

    #[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<'_, S>) -> bool {
        match self {
            Some(ref inner) => inner.enabled(metadata, ctx),
            None => true,
        }
    }

    #[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<'_, S>) {
        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<'_, S>) {
        if let Some(ref inner) = self {
            inner.on_follows_from(span, follows, ctx);
        }
    }

    #[inline]
    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        if let Some(ref inner) = self {
            inner.on_event(event, ctx);
        }
    }

    #[inline]
    fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
        if let Some(ref inner) = self {
            inner.on_enter(id, ctx);
        }
    }

    #[inline]
    fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
        if let Some(ref inner) = self {
            inner.on_exit(id, ctx);
        }
    }

    #[inline]
    fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
        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<'_, S>) {
        if let Some(ref inner) = self {
            inner.on_id_change(old, new, ctx)
        }
    }

    #[doc(hidden)]
    #[inline]
    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
        if id == TypeId::of::<Self>() {
            Some(self as *const _ as *const ())
        } else {
            self.as_ref().and_then(|inner| inner.downcast_raw(id))
        }
    }
}

#[cfg(feature = "registry")]
#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
impl<'a, L, S> LookupSpan<'a> for Layered<L, S>
where
    S: Subscriber + LookupSpan<'a>,
{
    type Data = S::Data;

    fn span_data(&'a self, id: &span::Id) -> Option<Self::Data> {
        self.inner.span_data(id)
    }
}

impl<L, S> Layered<L, S>
where
    S: Subscriber,
{
    fn ctx(&self) -> Context<'_, S> {
        Context {
            subscriber: Some(&self.inner),
        }
    }
}

// impl<L, S> Layered<L, S> {
//     // TODO(eliza): is there a compelling use-case for this being public?
//     pub(crate) fn into_inner(self) -> S {
//         self.inner
//     }
// }

// === impl SubscriberExt ===

impl<S: Subscriber> crate::sealed::Sealed for S {}
impl<S: Subscriber> SubscriberExt for S {}

// === impl Context ===

impl<'a, S> Context<'a, S>
where
    S: Subscriber,
{
    /// Returns the wrapped subscriber's view of the current span.
    #[inline]
    pub fn current_span(&self) -> span::Current {
        self.subscriber
            .map(Subscriber::current_span)
            // TODO: this would be more correct as "unknown", so perhaps
            // `tracing-core` should make `Current::unknown()` public?
            .unwrap_or_else(span::Current::none)
    }

    /// Returns whether the wrapped subscriber would enable the current span.
    #[inline]
    pub fn enabled(&self, metadata: &Metadata<'_>) -> bool {
        self.subscriber
            .map(|subscriber| subscriber.enabled(metadata))
            // If this context is `None`, we are registering a callsite, so
            // return `true` so that the layer does not incorrectly assume that
            // the inner subscriber has disabled this metadata.
            // TODO(eliza): would it be more correct for this to return an `Option`?
            .unwrap_or(true)
    }

    /// Records the provided `event` with the wrapped subscriber.
    ///
    /// # Notes
    ///
    /// - The subscriber is free to expect that the event's callsite has been
    ///   [registered][register], and may panic or fail to observe the event if this is
    ///   not the case. The `tracing` crate's macros ensure that all events are
    ///   registered, but if the event is constructed through other means, the
    ///   user is responsible for ensuring that [`register_callsite`][register]
    ///   has been called prior to calling this method.
    /// - This does _not_ call [`enabled`] on the inner subscriber. If the
    ///   caller wishes to apply the wrapped subscriber's filter before choosing
    ///   whether to record the event, it may first call [`Context::enabled`] to
    ///   check whether the event would be enabled. This allows `Layer`s to
    ///   elide constructing the event if it would not be recorded.
    ///
    /// [register]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html#method.register_callsite
    /// [`enabled`]: https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait.Subscriber.html#method.enabled
    /// [`Context::enabled`]: #method.enabled
    #[inline]
    pub fn event(&self, event: &Event<'_>) {
        if let Some(ref subscriber) = self.subscriber {
            subscriber.event(event);
        }
    }

    /// Returns a [`SpanRef`] for the parent span of the given [`Event`], if
    /// it has a parent.
    ///
    /// If the event has an explicitly overridden parent, this method returns
    /// a reference to that span. If the event's parent is the current span,
    /// this returns a reference to the current span, if there is one. If this
    /// returns `None`, then either the event's parent was explicitly set to
    /// `None`, or the event's parent was defined contextually, but no span
    /// is currently entered.
    ///
    /// Compared to [`Context::current_span`] and [`Context::lookup_current`],
    /// this respects overrides provided by the [`Event`].
    ///
    /// Compared to [`Event::parent`], this automatically falls back to the contextual
    /// span, if required.
    ///
    /// ```rust
    /// use tracing::{Event, Subscriber};
    /// use tracing_subscriber::{
    ///     layer::{Context, Layer},
    ///     prelude::*,
    ///     registry::LookupSpan,
    /// };
    ///
    /// struct PrintingLayer;
    /// impl<S> Layer<S> for PrintingLayer
    /// where
    ///     S: Subscriber + for<'lookup> LookupSpan<'lookup>,
    /// {
    ///     fn on_event(&self, event: &Event, ctx: Context<S>) {
    ///         let span = ctx.event_span(event);
    ///         println!("Event in span: {:?}", span.map(|s| s.name()));
    ///     }
    /// }
    ///
    /// tracing::subscriber::with_default(tracing_subscriber::registry().with(PrintingLayer), || {
    ///     tracing::info!("no span");
    ///     // Prints: Event in span: None
    ///
    ///     let span = tracing::info_span!("span");
    ///     tracing::info!(parent: &span, "explicitly specified");
    ///     // Prints: Event in span: Some("span")
    ///
    ///     let _guard = span.enter();
    ///     tracing::info!("contextual span");
    ///     // Prints: Event in span: Some("span")
    /// });
    /// ```
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    #[inline]
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn event_span(&self, event: &Event<'_>) -> Option<SpanRef<'_, S>>
    where
        S: for<'lookup> LookupSpan<'lookup>,
    {
        if event.is_root() {
            None
        } else if event.is_contextual() {
            self.lookup_current()
        } else {
            event.parent().and_then(|id| self.span(id))
        }
    }

    /// Returns metadata for the span with the given `id`, if it exists.
    ///
    /// If this returns `None`, then no span exists for that ID (either it has
    /// closed or the ID is invalid).
    #[inline]
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn metadata(&self, id: &span::Id) -> Option<&'static Metadata<'static>>
    where
        S: for<'lookup> LookupSpan<'lookup>,
    {
        let span = self.subscriber.as_ref()?.span(id)?;
        Some(span.metadata())
    }

    /// Returns [stored data] for the span with the given `id`, if it exists.
    ///
    /// If this returns `None`, then no span exists for that ID (either it has
    /// closed or the ID is invalid).
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    ///
    /// [stored data]: ../registry/struct.SpanRef.html
    #[inline]
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn span(&self, id: &span::Id) -> Option<registry::SpanRef<'_, S>>
    where
        S: for<'lookup> LookupSpan<'lookup>,
    {
        self.subscriber.as_ref()?.span(id)
    }

    /// Returns `true` if an active span exists for the given `Id`.
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    #[inline]
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn exists(&self, id: &span::Id) -> bool
    where
        S: for<'lookup> LookupSpan<'lookup>,
    {
        self.subscriber.as_ref().and_then(|s| s.span(id)).is_some()
    }

    /// Returns [stored data] for the span that the wrapped subscriber considers
    /// to be the current.
    ///
    /// If this returns `None`, then we are not currently within a span.
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    ///
    /// [stored data]: ../registry/struct.SpanRef.html
    #[inline]
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn lookup_current(&self) -> Option<registry::SpanRef<'_, S>>
    where
        S: for<'lookup> LookupSpan<'lookup>,
    {
        let subscriber = self.subscriber.as_ref()?;
        let current = subscriber.current_span();
        let id = current.id()?;
        let span = subscriber.span(&id);
        debug_assert!(
            span.is_some(),
            "the subscriber should have data for the current span ({:?})!",
            id,
        );
        span
    }

    /// Returns an iterator over the [stored data] for all the spans in the
    /// current context, starting the root of the trace tree and ending with
    /// the current span.
    ///
    /// If this iterator is empty, then there are no spans in the current context.
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    ///
    /// [stored data]: ../registry/struct.SpanRef.html
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    #[deprecated(
        note = "equivalent to `self.current_span().id().and_then(|id| self.span_scope(id).from_root())` but consider passing an explicit ID instead of relying on the contextual span",
        since = "0.2.19"
    )]
    #[allow(deprecated)]
    pub fn scope(&self) -> Scope<'_, S>
    where
        S: for<'lookup> registry::LookupSpan<'lookup>,
    {
        Scope(
            self.lookup_current()
                .as_ref()
                .map(registry::SpanRef::scope)
                .map(registry::Scope::from_root)
                .into_iter()
                .flatten(),
        )
    }

    /// Returns an iterator over the [stored data] for all the spans in the
    /// current context, starting with the specified span and ending with the
    /// root of the trace tree and ending with the current span.
    ///
    /// <div class="information">
    ///     <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div>
    /// </div>
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: Compared to <a href="#method.scope"><code>scope</code></a> this
    /// returns the spans in reverse order (from leaf to root). Use
    /// <a href="../registry/struct.Scope.html#method.from_root"><code>Scope::from_root</code></a>
    /// in case root-to-leaf ordering is desired.
    /// </pre></div>
    ///
    /// <div class="information">
    ///     <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div>
    /// </div>
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    ///
    /// [stored data]: ../registry/struct.SpanRef.html
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn span_scope(&self, id: &span::Id) -> Option<registry::Scope<'_, S>>
    where
        S: for<'lookup> registry::LookupSpan<'lookup>,
    {
        Some(self.span(id)?.scope())
    }

    /// Returns an iterator over the [stored data] for all the spans in the
    /// current context, starting with the parent span of the specified event,
    /// and ending with the root of the trace tree and ending with the current span.
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: Compared to <a href="#method.scope"><code>scope</code></a> this
    /// returns the spans in reverse order (from leaf to root). Use
    /// <a href="../registry/struct.Scope.html#method.from_root"><code>Scope::from_root</code></a>
    /// in case root-to-leaf ordering is desired.
    /// </pre></div>
    ///
    /// <div class="example-wrap" style="display:inline-block">
    /// <pre class="ignore" style="white-space:normal;font:inherit;">
    /// <strong>Note</strong>: This requires the wrapped subscriber to implement the
    /// <a href="../registry/trait.LookupSpan.html"><code>LookupSpan</code></a> trait.
    /// See the documentation on <a href="./struct.Context.html"><code>Context</code>'s
    /// declaration</a> for details.
    /// </pre></div>
    ///
    /// [stored data]: ../registry/struct.SpanRef.html
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn event_scope(&self, event: &Event<'_>) -> Option<registry::Scope<'_, S>>
    where
        S: for<'lookup> registry::LookupSpan<'lookup>,
    {
        Some(self.event_span(event)?.scope())
    }
}

impl<'a, S> Context<'a, S> {
    pub(crate) fn none() -> Self {
        Self { subscriber: None }
    }
}

impl<'a, S> Clone for Context<'a, S> {
    #[inline]
    fn clone(&self) -> Self {
        let subscriber = self.subscriber.as_ref().copied();
        Context { subscriber }
    }
}

// === impl Identity ===
//
impl<S: Subscriber> Layer<S> for Identity {}

impl Identity {
    /// Returns a new `Identity` layer.
    pub fn new() -> Self {
        Self { _p: () }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::sync::{Arc, Mutex};

    use super::*;

    pub(crate) struct NopSubscriber;

    impl Subscriber for NopSubscriber {
        fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest {
            Interest::never()
        }

        fn enabled(&self, _: &Metadata<'_>) -> bool {
            false
        }

        fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
            span::Id::from_u64(1)
        }

        fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
        fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
        fn event(&self, _: &Event<'_>) {}
        fn enter(&self, _: &span::Id) {}
        fn exit(&self, _: &span::Id) {}
    }

    struct NopLayer;
    impl<S: Subscriber> Layer<S> for NopLayer {}

    #[allow(dead_code)]
    struct NopLayer2;
    impl<S: Subscriber> Layer<S> for NopLayer2 {}

    /// A layer that holds a string.
    ///
    /// Used to test that pointers returned by downcasting are actually valid.
    struct StringLayer(String);
    impl<S: Subscriber> Layer<S> for StringLayer {}
    struct StringLayer2(String);
    impl<S: Subscriber> Layer<S> for StringLayer2 {}

    struct StringLayer3(String);
    impl<S: Subscriber> Layer<S> for StringLayer3 {}

    pub(crate) struct StringSubscriber(String);

    impl Subscriber for StringSubscriber {
        fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest {
            Interest::never()
        }

        fn enabled(&self, _: &Metadata<'_>) -> bool {
            false
        }

        fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
            span::Id::from_u64(1)
        }

        fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
        fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
        fn event(&self, _: &Event<'_>) {}
        fn enter(&self, _: &span::Id) {}
        fn exit(&self, _: &span::Id) {}
    }

    fn assert_subscriber(_s: impl Subscriber) {}

    #[test]
    fn layer_is_subscriber() {
        let s = NopLayer.with_subscriber(NopSubscriber);
        assert_subscriber(s)
    }

    #[test]
    fn two_layers_are_subscriber() {
        let s = NopLayer.and_then(NopLayer).with_subscriber(NopSubscriber);
        assert_subscriber(s)
    }

    #[test]
    fn three_layers_are_subscriber() {
        let s = NopLayer
            .and_then(NopLayer)
            .and_then(NopLayer)
            .with_subscriber(NopSubscriber);
        assert_subscriber(s)
    }

    #[test]
    fn downcasts_to_subscriber() {
        let s = NopLayer
            .and_then(NopLayer)
            .and_then(NopLayer)
            .with_subscriber(StringSubscriber("subscriber".into()));
        let subscriber = <dyn Subscriber>::downcast_ref::<StringSubscriber>(&s)
            .expect("subscriber should downcast");
        assert_eq!(&subscriber.0, "subscriber");
    }

    #[test]
    fn downcasts_to_layer() {
        let s = StringLayer("layer_1".into())
            .and_then(StringLayer2("layer_2".into()))
            .and_then(StringLayer3("layer_3".into()))
            .with_subscriber(NopSubscriber);
        let layer =
            <dyn Subscriber>::downcast_ref::<StringLayer>(&s).expect("layer 1 should downcast");
        assert_eq!(&layer.0, "layer_1");
        let layer =
            <dyn Subscriber>::downcast_ref::<StringLayer2>(&s).expect("layer 2 should downcast");
        assert_eq!(&layer.0, "layer_2");
        let layer =
            <dyn Subscriber>::downcast_ref::<StringLayer3>(&s).expect("layer 3 should downcast");
        assert_eq!(&layer.0, "layer_3");
    }

    #[test]
    fn context_event_span() {
        let last_event_span = Arc::new(Mutex::new(None));

        struct RecordingLayer {
            last_event_span: Arc<Mutex<Option<&'static str>>>,
        }

        impl<S> Layer<S> for RecordingLayer
        where
            S: Subscriber + for<'lookup> LookupSpan<'lookup>,
        {
            fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
                let span = ctx.event_span(event);
                *self.last_event_span.lock().unwrap() = span.map(|s| s.name());
            }
        }

        tracing::subscriber::with_default(
            crate::registry().with(RecordingLayer {
                last_event_span: last_event_span.clone(),
            }),
            || {
                tracing::info!("no span");
                assert_eq!(*last_event_span.lock().unwrap(), None);

                let parent = tracing::info_span!("explicit");
                tracing::info!(parent: &parent, "explicit span");
                assert_eq!(*last_event_span.lock().unwrap(), Some("explicit"));

                let _guard = tracing::info_span!("contextual").entered();
                tracing::info!("contextual span");
                assert_eq!(*last_event_span.lock().unwrap(), Some("contextual"));
            },
        );
    }
}