tracing_subscriber_init/initialize.rs
1// Copyright (c) 2023 tracing-subscriber-init developers
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use anyhow::Result;
10use tracing::subscriber::DefaultGuard;
11use tracing_subscriber::{
12 prelude::__tracing_subscriber_SubscriberExt, registry, util::SubscriberInitExt, Layer, Registry,
13};
14
15/// Creates a [`Registry`](tracing_subscriber::registry::Registry), adds the given [`Layer`s](tracing_subscriber::Layer)
16/// to it, and sets itself as the default subscriber in the current scope, returning a guard that will unset it
17/// when dropped.
18///
19/// See [`set_default`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/util/trait.SubscriberInitExt.html#method.set_default)
20///
21/// # Errors
22/// * An error can be thrown on registry initialization
23///
24#[must_use]
25pub fn set_default(layers: Vec<Box<dyn Layer<Registry> + Send + Sync + 'static>>) -> DefaultGuard {
26 registry().with(layers).set_default()
27}
28
29/// Creates a [`Registry`](tracing_subscriber::registry::Registry), adds the given [`Layer`s](tracing_subscriber::Layer)
30/// to it, and attempts to set itself as the global default subscriber in the current scope, panicking if this fails.
31///
32/// See [`init`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/util/trait.SubscriberInitExt.html#method.init)
33///
34/// # Errors
35/// * An error can be thrown on registry initialization
36///
37pub fn init(layers: Vec<Box<dyn Layer<Registry> + Send + Sync + 'static>>) {
38 registry().with(layers).init();
39}
40
41/// Creates a [`Registry`](tracing_subscriber::registry::Registry), adds the given [`Layer`s](tracing_subscriber::Layer)
42/// to it, and attempts to set self as the global default subscriber in the current scope, returning an error if one is already set.
43///
44/// See [`try_init`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/util/trait.SubscriberInitExt.html#method.try_init)
45///
46/// # Errors
47/// * An error can be thrown on registry initialization
48///
49pub fn try_init(layers: Vec<Box<dyn Layer<Registry> + Send + Sync + 'static>>) -> Result<()> {
50 Ok(registry().with(layers).try_init()?)
51}
52
53#[cfg(test)]
54mod test {
55 use tracing_subscriber::Layer;
56
57 use crate::{full_filtered, TestAll};
58
59 use super::set_default;
60
61 #[test]
62 fn set_default_works() {
63 let config = TestAll;
64 let layer = full_filtered(&config);
65 let _unused = set_default(vec![layer.boxed()]);
66 }
67}