hds_console_subscriber/
builder.rs

1use super::{ConsoleLayer, Server};
2#[cfg(unix)]
3use std::path::Path;
4use std::{
5    net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs},
6    path::PathBuf,
7    thread,
8    time::Duration,
9};
10use tokio::runtime;
11use tracing::Subscriber;
12use tracing_subscriber::{
13    filter::{self, FilterFn},
14    layer::{Layer, SubscriberExt},
15    prelude::*,
16    registry::LookupSpan,
17};
18
19/// Builder for configuring [`ConsoleLayer`]s.
20#[derive(Clone, Debug)]
21pub struct Builder {
22    /// The maximum capacity for the channel of events from the subscriber to
23    /// the aggregator task.
24    pub(super) event_buffer_capacity: usize,
25
26    /// The maximum number of updates to buffer per-client before the client is
27    /// dropped.
28    pub(super) client_buffer_capacity: usize,
29
30    /// The interval between publishing updates to clients.
31    pub(crate) publish_interval: Duration,
32
33    /// How long to retain data for completed events.
34    pub(crate) retention: Duration,
35
36    /// The address on which to serve the RPC server.
37    pub(super) server_addr: ServerAddr,
38
39    /// If and where to save a recording of the events.
40    pub(super) recording_path: Option<PathBuf>,
41
42    /// The filter environment variable to use for `tracing` events.
43    pub(super) filter_env_var: String,
44
45    /// Whether to trace events coming from the subscriber thread
46    self_trace: bool,
47
48    /// The maximum value for the task poll duration histogram.
49    ///
50    /// Any polls exceeding this duration will be clamped to this value. Higher
51    /// values will result in more memory usage.
52    pub(super) poll_duration_max: Duration,
53
54    /// The maximum value for the task scheduled duration histogram.
55    ///
56    /// Any scheduled times exceeding this duration will be clamped to this
57    /// value. Higher values will result in more memory usage.
58    pub(super) scheduled_duration_max: Duration,
59
60    /// Whether to enable the grpc-web support.
61    #[cfg(feature = "grpc-web")]
62    enable_grpc_web: bool,
63}
64
65impl Default for Builder {
66    fn default() -> Self {
67        Self {
68            event_buffer_capacity: ConsoleLayer::DEFAULT_EVENT_BUFFER_CAPACITY,
69            client_buffer_capacity: ConsoleLayer::DEFAULT_CLIENT_BUFFER_CAPACITY,
70            publish_interval: ConsoleLayer::DEFAULT_PUBLISH_INTERVAL,
71            retention: ConsoleLayer::DEFAULT_RETENTION,
72            poll_duration_max: ConsoleLayer::DEFAULT_POLL_DURATION_MAX,
73            scheduled_duration_max: ConsoleLayer::DEFAULT_SCHEDULED_DURATION_MAX,
74            server_addr: ServerAddr::Tcp(SocketAddr::new(Server::DEFAULT_IP, Server::DEFAULT_PORT)),
75            recording_path: None,
76            filter_env_var: "RUST_LOG".to_string(),
77            self_trace: false,
78            #[cfg(feature = "grpc-web")]
79            enable_grpc_web: false,
80        }
81    }
82}
83
84impl Builder {
85    /// Sets the maximum capacity for the channel of events sent from subscriber
86    /// layers to the aggregator task.
87    ///
88    /// When this channel is at capacity, additional events will be dropped.
89    ///
90    /// By default, this is [`ConsoleLayer::DEFAULT_EVENT_BUFFER_CAPACITY`].
91    pub fn event_buffer_capacity(self, event_buffer_capacity: usize) -> Self {
92        Self {
93            event_buffer_capacity,
94            ..self
95        }
96    }
97
98    /// Sets the maximum capacity of updates to buffer for each subscribed
99    /// client, if that client is not reading from the RPC stream.
100    ///
101    /// When this channel is at capacity, the client may be disconnected.
102    ///
103    /// By default, this is [`ConsoleLayer::DEFAULT_CLIENT_BUFFER_CAPACITY`].
104    pub fn client_buffer_capacity(self, client_buffer_capacity: usize) -> Self {
105        Self {
106            client_buffer_capacity,
107            ..self
108        }
109    }
110
111    /// Sets how frequently updates are published to clients.
112    ///
113    /// A shorter duration will allow clients to update more frequently, but may
114    /// result in the program spending more time preparing task data updates.
115    ///
116    /// By default, this is [`ConsoleLayer::DEFAULT_PUBLISH_INTERVAL`].
117    /// Methods like [`init`][`crate::init`] and [`spawn`][`crate::spawn`] will
118    /// take the value from the `TOKIO_CONSOLE_PUBLISH_INTERVAL` [environment
119    /// variable] before falling back on that default.
120    ///
121    /// [environment variable]: `Builder::with_default_env`
122    pub fn publish_interval(self, publish_interval: Duration) -> Self {
123        Self {
124            publish_interval,
125            ..self
126        }
127    }
128
129    /// Sets how long data is retained for completed tasks.
130    ///
131    /// A longer duration will allow more historical data to be replayed by
132    /// clients, but will result in increased memory usage. A shorter duration
133    /// will reduce memory usage, but less historical data from completed tasks
134    /// will be retained.
135    ///
136    /// By default, this is [`ConsoleLayer::DEFAULT_RETENTION`]. Methods
137    /// like [`init`][`crate::init`] and [`spawn`][`crate::spawn`] will take the
138    /// value from the `TOKIO_CONSOLE_RETENTION` [environment variable] before
139    /// falling back on that default.
140    ///
141    /// [environment variable]: `Builder::with_default_env`
142    pub fn retention(self, retention: Duration) -> Self {
143        Self { retention, ..self }
144    }
145
146    /// Sets the socket address on which to serve the RPC server.
147    ///
148    /// By default, the server is bound on the IP address [`Server::DEFAULT_IP`]
149    /// on port [`Server::DEFAULT_PORT`]. Methods like
150    /// [`init`][`crate::init`] and [`spawn`][`crate::spawn`] will parse the
151    /// socket address from the `TOKIO_CONSOLE_BIND` [environment variable]
152    /// before falling back on constructing a socket address from those
153    /// defaults.
154    ///
155    /// The socket address can be either a TCP socket address or a
156    /// [Unix domain socket] (UDS) address. Unix domain sockets are only
157    /// supported on Unix-compatible operating systems, such as Linux, BSDs,
158    /// and macOS.
159    ///
160    /// Each call to this method will overwrite the previously set value.
161    ///
162    /// # Examples
163    ///
164    /// Connect to the TCP address `localhost:1234`:
165    ///
166    /// ```
167    /// # use hds_console_subscriber::Builder;
168    /// use std::net::Ipv4Addr;
169    /// let builder = Builder::default().server_addr((Ipv4Addr::LOCALHOST, 1234));
170    /// ```
171    ///
172    /// Connect to the UDS address `/tmp/tokio-console`:
173    ///
174    /// ```
175    /// # use hds_console_subscriber::Builder;
176    /// # #[cfg(unix)]
177    /// use std::path::Path;
178    ///
179    /// // Unix domain sockets are only available on Unix-compatible operating systems.
180    /// #[cfg(unix)]
181    /// let builder = Builder::default().server_addr(Path::new("/tmp/tokio-console"));
182    /// ```
183    ///
184    /// [environment variable]: `Builder::with_default_env`
185    /// [Unix domain socket]: https://en.wikipedia.org/wiki/Unix_domain_socket
186    pub fn server_addr(self, server_addr: impl Into<ServerAddr>) -> Self {
187        Self {
188            server_addr: server_addr.into(),
189            ..self
190        }
191    }
192
193    /// Sets the path to record the events to the file system.
194    ///
195    /// By default, this is initially `None`. Methods like
196    /// [`init`][`crate::init`] and [`spawn`][`crate::spawn`] will take the
197    /// value from the `TOKIO_CONSOLE_RECORD_PATH` [environment variable] before
198    /// falling back on that default.
199    ///
200    /// [environment variable]: `Builder::with_default_env`
201    pub fn recording_path(self, path: impl Into<PathBuf>) -> Self {
202        Self {
203            recording_path: Some(path.into()),
204            ..self
205        }
206    }
207
208    /// Sets the environment variable used to configure which `tracing` events
209    /// are logged to stdout.
210    ///
211    /// The [`Builder::init`] method configures the default `tracing`
212    /// subscriber. In addition to a [`ConsoleLayer`], the subscriber
213    /// constructed by `init` includes a [`fmt::Layer`] for logging events to
214    /// stdout. What `tracing` events that layer will log is determined by the
215    /// value of an environment variable; this method configures which
216    /// environment variable is read to determine the log filter.
217    ///
218    /// This environment variable does not effect what spans and events are
219    /// recorded by the [`ConsoleLayer`]. Therefore, this method will have no
220    /// effect if the builder is used with [`Builder::spawn`] or
221    /// [`Builder::build`].
222    ///
223    /// The default environment variable is `RUST_LOG`. See [here] for details
224    /// on the syntax for configuring the filter.
225    ///
226    /// [`fmt::Layer`]: https://docs.rs/tracing-subscriber/0.3/tracing_subscriber/fmt/index.html
227    /// [here]: https://docs.rs/tracing-subscriber/0.3/tracing_subscriber/filter/targets/struct.Targets.html
228    pub fn filter_env_var(self, filter_env_var: impl Into<String>) -> Self {
229        Self {
230            filter_env_var: filter_env_var.into(),
231            ..self
232        }
233    }
234
235    /// Sets the maximum value for task poll duration histograms.
236    ///
237    /// Any poll durations exceeding this value will be clamped down to this
238    /// duration and recorded as an outlier.
239    ///
240    /// By default, this is [one second]. Higher values will increase per-task
241    /// memory usage.
242    ///
243    /// [one second]: ConsoleLayer::DEFAULT_POLL_DURATION_MAX
244    pub fn poll_duration_histogram_max(self, max: Duration) -> Self {
245        Self {
246            poll_duration_max: max,
247            ..self
248        }
249    }
250
251    /// Sets the maximum value for task scheduled duration histograms.
252    ///
253    /// Any scheduled duration (the time from a task being woken until it is next
254    /// polled) exceeding this value will be clamped down to this duration
255    /// and recorded as an outlier.
256    ///
257    /// By default, this is [one second]. Higher values will increase per-task
258    /// memory usage.
259    ///
260    /// [one second]: ConsoleLayer::DEFAULT_SCHEDULED_DURATION_MAX
261    pub fn scheduled_duration_histogram_max(self, max: Duration) -> Self {
262        Self {
263            scheduled_duration_max: max,
264            ..self
265        }
266    }
267
268    /// Sets whether tasks, resources, and async ops from the console
269    /// subscriber thread are recorded.
270    ///
271    /// By default, events from the console subscriber are discarded and
272    /// not exported to clients.
273    pub fn enable_self_trace(self, self_trace: bool) -> Self {
274        Self { self_trace, ..self }
275    }
276
277    /// Sets whether to enable the grpc-web support.
278    ///
279    /// By default, this is `false`. If enabled, the console subscriber will
280    /// serve the gRPC-Web protocol in addition to the standard gRPC protocol.
281    /// This is useful for serving the console subscriber to web clients.
282    /// Please be aware that the current default server port is set to 6669.
283    /// However, certain browsers may restrict this port due to security reasons.
284    /// If you encounter issues with this, consider changing the port to an
285    /// alternative one that is not commonly blocked by browsers.
286    ///
287    /// [`serve_with_grpc_web`] is used to provide more advanced configuration
288    /// for the gRPC-Web server.
289    ///
290    /// [`serve_with_grpc_web`]: crate::Server::serve_with_grpc_web
291    #[cfg(feature = "grpc-web")]
292    pub fn enable_grpc_web(self, enable_grpc_web: bool) -> Self {
293        Self {
294            enable_grpc_web,
295            ..self
296        }
297    }
298
299    /// Completes the builder, returning a [`ConsoleLayer`] and [`Server`] task.
300    pub fn build(self) -> (ConsoleLayer, Server) {
301        ConsoleLayer::build(self)
302    }
303
304    /// Configures this builder from a standard set of environment variables:
305    ///
306    /// | **Environment Variable**         | **Purpose**                                                  | **Default Value** |
307    /// |----------------------------------|--------------------------------------------------------------|-------------------|
308    /// | `TOKIO_CONSOLE_RETENTION`        | The duration of seconds to accumulate completed tracing data | 3600s (1h)        |
309    /// | `TOKIO_CONSOLE_BIND`             | a HOST:PORT description, such as `localhost:1234`            | `127.0.0.1:6669`  |
310    /// | `TOKIO_CONSOLE_PUBLISH_INTERVAL` | The duration to wait between sending updates to the console  | 1000ms (1s)       |
311    /// | `TOKIO_CONSOLE_RECORD_PATH`      | The file path to save a recording                            | None              |
312    pub fn with_default_env(mut self) -> Self {
313        if let Some(retention) = duration_from_env("TOKIO_CONSOLE_RETENTION") {
314            self.retention = retention;
315        }
316
317        if let Ok(bind) = std::env::var("TOKIO_CONSOLE_BIND") {
318            self.server_addr = ServerAddr::Tcp(
319                bind.to_socket_addrs()
320                    .expect(
321                        "TOKIO_CONSOLE_BIND must be formatted as HOST:PORT, such as localhost:4321",
322                    )
323                    .next()
324                    .expect("tokio console could not resolve TOKIO_CONSOLE_BIND"),
325            );
326        }
327
328        if let Some(interval) = duration_from_env("TOKIO_CONSOLE_PUBLISH_INTERVAL") {
329            self.publish_interval = interval;
330        }
331
332        if let Ok(path) = std::env::var("TOKIO_CONSOLE_RECORD_PATH") {
333            self.recording_path = Some(path.into());
334        }
335
336        self
337    }
338
339    /// Initializes the console [tracing `Subscriber`][sub] and starts the console
340    /// subscriber [`Server`] on its own background thread.
341    ///
342    /// This function represents the easiest way to get started using
343    /// tokio-console.
344    ///
345    /// In addition to the [`ConsoleLayer`], which collects instrumentation data
346    /// consumed by the console, the default [`Subscriber`][sub] initialized by this
347    /// function also includes a [`tracing_subscriber::fmt`] layer, which logs
348    /// tracing spans and events to stdout. Which spans and events are logged will
349    /// be determined by an environment variable, which defaults to `RUST_LOG`.
350    /// The [`Builder::filter_env_var`] method can be used to override the
351    /// environment variable used to configure the log filter.
352    ///
353    /// **Note**: this function sets the [default `tracing` subscriber][default]
354    /// for your application. If you need to add additional layers to a subscriber,
355    /// see [`spawn`].
356    ///
357    /// # Panics
358    ///
359    /// * If the subscriber's background thread could not be spawned.
360    /// * If the [default `tracing` subscriber][default] has already been set.
361    ///
362    /// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber
363    /// [sub]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
364    /// [`tracing_subscriber::fmt`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/fmt/index.html
365    /// [`Server`]: crate::Server
366    ///
367    /// # Configuration
368    ///
369    /// Tokio console subscriber is configured with sensible defaults for most
370    /// use cases. If you need to tune these parameters, several environmental
371    /// configuration variables are available:
372    ///
373    /// | **Environment Variable**            | **Purpose**                                                               | **Default Value** |
374    /// |-------------------------------------|---------------------------------------------------------------------------|-------------------|
375    /// | `TOKIO_CONSOLE_RETENTION`           | The number of seconds to accumulate completed tracing data                | 3600s (1h)        |
376    /// | `TOKIO_CONSOLE_BIND`                | A HOST:PORT description, such as `localhost:1234`                         | `127.0.0.1:6669`  |
377    /// | `TOKIO_CONSOLE_PUBLISH_INTERVAL`    | The number of milliseconds to wait between sending updates to the console | 1000ms (1s)       |
378    /// | `TOKIO_CONSOLE_RECORD_PATH`         | The file path to save a recording                                         | None              |
379    /// | `RUST_LOG`                          | Configures what events are logged events. See [`Targets`] for details.    | "error"           |
380    ///
381    /// If the "env-filter" crate feature flag is enabled, the `RUST_LOG`
382    /// environment variable will be parsed using the [`EnvFilter`] type from
383    /// `tracing-subscriber`. If the "env-filter" feature is **not** enabled, the
384    /// [`Targets`] filter is used instead. The `EnvFilter` type accepts all the
385    /// same syntax as `Targets`, but with the added ability to filter dynamically
386    /// on span field values. See the documentation for those types for details.
387    ///
388    /// # Further customization
389    ///
390    /// To add additional layers or replace the format layer, replace
391    /// `hds_console_subscriber::Builder::init` with:
392    ///
393    /// ```rust
394    /// use tracing_subscriber::prelude::*;
395    ///
396    /// let console_layer = hds_console_subscriber::ConsoleLayer::builder().spawn();
397    ///
398    /// tracing_subscriber::registry()
399    ///     .with(console_layer)
400    ///     .with(tracing_subscriber::fmt::layer())
401    /// //  .with(..potential additional layer..)
402    ///     .init();
403    /// ```
404    ///
405    /// [`Targets`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/filter/struct.Targets.html
406    /// [`EnvFilter`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/filter/struct.EnvFilter.html
407    pub fn init(self) {
408        #[cfg(feature = "env-filter")]
409        type Filter = filter::EnvFilter;
410        #[cfg(not(feature = "env-filter"))]
411        type Filter = filter::Targets;
412
413        let fmt_filter = std::env::var(&self.filter_env_var)
414            .ok()
415            .and_then(|log_filter| match log_filter.parse::<Filter>() {
416                Ok(targets) => Some(targets),
417                Err(e) => {
418                    eprintln!(
419                        "failed to parse filter environment variable `{}={:?}`: {}",
420                        &self.filter_env_var, log_filter, e
421                    );
422                    None
423                }
424            })
425            .unwrap_or_else(|| {
426                "error"
427                    .parse::<Filter>()
428                    .expect("`error` filter should always parse successfully")
429            });
430
431        let console_layer = self.spawn();
432
433        tracing_subscriber::registry()
434            .with(console_layer)
435            .with(tracing_subscriber::fmt::layer().with_filter(fmt_filter))
436            .init();
437    }
438
439    /// Returns a new `tracing` [`Layer`] consisting of a [`ConsoleLayer`]
440    /// and a [filter] that enables the spans and events required by the console.
441    ///
442    /// This function spawns the console subscriber's [`Server`] in its own Tokio
443    /// runtime in a background thread.
444    ///
445    /// Unlike [`init`], this function does not set the default subscriber, allowing
446    /// additional [`Layer`]s to be added.
447    ///
448    /// [subscriber]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html
449    /// [filter]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/targets/struct.Targets.html
450    /// [`Layer`]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/trait.Layer.html
451    /// [`Server`]: crate::Server
452    ///
453    /// # Panics
454    ///
455    /// * If the subscriber's background thread could not be spawned.
456    ///
457    /// # Configuration
458    ///
459    /// `hds_console_subscriber::build` supports all of the environmental
460    /// configuration described at [`hds_console_subscriber::init`].
461    ///
462    /// # Differences from `init`
463    ///
464    /// Unlike [`hds_console_subscriber::init`], this function does *not* add a
465    /// [`tracing_subscriber::fmt`] layer to the configured `Subscriber`. This means
466    /// that this function will not log spans and events based on the value of the
467    /// `RUST_LOG` environment variable. Instead, a user-provided [`fmt::Layer`] can
468    /// be added in order to customize the log format.
469    ///
470    /// You must call [`.init()`] on the final subscriber in order to [set the
471    /// subscriber as the default][default].
472    ///
473    /// # Examples
474    ///
475    /// ```rust
476    /// use tracing_subscriber::prelude::*;
477    ///
478    /// let console_layer = hds_console_subscriber::ConsoleLayer::builder()
479    ///     .with_default_env()
480    ///     .spawn();
481    ///
482    /// tracing_subscriber::registry()
483    ///     .with(console_layer)
484    ///     .with(tracing_subscriber::fmt::layer())
485    /// //  .with(...)
486    ///     .init();
487    /// ```
488    /// [`.init()`]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/util/trait.SubscriberInitExt.html
489    /// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber
490    /// [sub]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
491    /// [`tracing_subscriber::fmt`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/fmt/index.html
492    /// [`fmt::Layer`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/fmt/struct.Layer.html
493    /// [`hds_console_subscriber::init`]: crate::init()
494    #[must_use = "a `Layer` must be added to a `tracing::Subscriber` in order to be used"]
495    pub fn spawn<S>(self) -> impl Layer<S>
496    where
497        S: Subscriber + for<'a> LookupSpan<'a>,
498    {
499        fn console_filter(meta: &tracing::Metadata<'_>) -> bool {
500            // events will have *targets* beginning with "runtime"
501            if meta.is_event() {
502                return meta.target().starts_with("runtime") || meta.target().starts_with("tokio");
503            }
504
505            // spans will have *names* beginning with "runtime". for backwards
506            // compatibility with older Tokio versions, enable anything with the `tokio`
507            // target as well.
508            meta.name().starts_with("runtime.") || meta.target().starts_with("tokio")
509        }
510
511        let self_trace = self.self_trace;
512        #[cfg(feature = "grpc-web")]
513        let enable_grpc_web = self.enable_grpc_web;
514
515        let (layer, server) = self.build();
516        let filter =
517            FilterFn::new(console_filter as for<'r, 's> fn(&'r tracing::Metadata<'s>) -> bool);
518        let layer = layer.with_filter(filter);
519
520        thread::Builder::new()
521            .name("console_subscriber".into())
522            .spawn(move || {
523                let _subscriber_guard;
524                if !self_trace {
525                    _subscriber_guard = tracing::subscriber::set_default(
526                        tracing_core::subscriber::NoSubscriber::default(),
527                    );
528                }
529                let runtime = runtime::Builder::new_current_thread()
530                    .enable_io()
531                    .enable_time()
532                    .build()
533                    .expect("console subscriber runtime initialization failed");
534                runtime.block_on(async move {
535                    #[cfg(feature = "grpc-web")]
536                    if enable_grpc_web {
537                        server
538                            .serve_with_grpc_web(tonic::transport::Server::builder())
539                            .await
540                            .expect("console subscriber server failed");
541                        return;
542                    }
543
544                    server
545                        .serve()
546                        .await
547                        .expect("console subscriber server failed")
548                });
549            })
550            .expect("console subscriber could not spawn thread");
551
552        layer
553    }
554}
555
556/// Specifies the address on which a [`Server`] should listen.
557///
558/// This type is passed as an argument to the [`Builder::server_addr`]
559/// method, and may be either a TCP socket address, or a [Unix domain socket]
560/// (UDS) address. Unix domain sockets are only supported on Unix-compatible
561/// operating systems, such as Linux, BSDs, and macOS.
562///
563/// [`Server`]: crate::Server
564/// [Unix domain socket]: https://en.wikipedia.org/wiki/Unix_domain_socket
565#[derive(Clone, Debug)]
566#[non_exhaustive]
567pub enum ServerAddr {
568    /// A TCP address.
569    Tcp(SocketAddr),
570    /// A Unix socket address.
571    #[cfg(unix)]
572    Unix(PathBuf),
573}
574
575impl From<SocketAddr> for ServerAddr {
576    fn from(addr: SocketAddr) -> ServerAddr {
577        ServerAddr::Tcp(addr)
578    }
579}
580
581impl From<SocketAddrV4> for ServerAddr {
582    fn from(addr: SocketAddrV4) -> ServerAddr {
583        ServerAddr::Tcp(addr.into())
584    }
585}
586
587impl From<SocketAddrV6> for ServerAddr {
588    fn from(addr: SocketAddrV6) -> ServerAddr {
589        ServerAddr::Tcp(addr.into())
590    }
591}
592
593impl<I> From<(I, u16)> for ServerAddr
594where
595    I: Into<IpAddr>,
596{
597    fn from(pieces: (I, u16)) -> ServerAddr {
598        ServerAddr::Tcp(pieces.into())
599    }
600}
601
602#[cfg(unix)]
603impl From<PathBuf> for ServerAddr {
604    fn from(path: PathBuf) -> ServerAddr {
605        ServerAddr::Unix(path)
606    }
607}
608
609#[cfg(unix)]
610impl<'a> From<&'a Path> for ServerAddr {
611    fn from(path: &'a Path) -> ServerAddr {
612        ServerAddr::Unix(path.to_path_buf())
613    }
614}
615
616/// Initializes the console [tracing `Subscriber`][sub] and starts the console
617/// subscriber [`Server`] on its own background thread.
618///
619/// This function represents the easiest way to get started using
620/// tokio-console.
621///
622/// In addition to the [`ConsoleLayer`], which collects instrumentation data
623/// consumed by the console, the default [`Subscriber`][sub] initialized by this
624/// function also includes a [`tracing_subscriber::fmt`] layer, which logs
625/// tracing spans and events to stdout. Which spans and events are logged will
626/// be determined by the `RUST_LOG` environment variable.
627///
628/// **Note**: this function sets the [default `tracing` subscriber][default]
629/// for your application. If you need to add additional layers to a subscriber,
630/// see [`spawn`].
631///
632/// # Panics
633///
634/// * If the subscriber's background thread could not be spawned.
635/// * If the [default `tracing` subscriber][default] has already been set.
636///
637/// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber
638/// [sub]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
639/// [`tracing_subscriber::fmt`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/fmt/index.html
640/// [`Server`]: crate::Server
641///
642/// # Configuration
643///
644/// Tokio console subscriber is configured with sensible defaults for most
645/// use cases. If you need to tune these parameters, several environmental
646/// configuration variables are available:
647///
648/// | **Environment Variable**            | **Purpose**                                                               | **Default Value** |
649/// |-------------------------------------|---------------------------------------------------------------------------|-------------------|
650/// | `TOKIO_CONSOLE_RETENTION`           | The number of seconds to accumulate completed tracing data                | 3600s (1h)        |
651/// | `TOKIO_CONSOLE_BIND`                | A HOST:PORT description, such as `localhost:1234`                         | `127.0.0.1:6669`  |
652/// | `TOKIO_CONSOLE_PUBLISH_INTERVAL`    | The number of milliseconds to wait between sending updates to the console | 1000ms (1s)       |
653/// | `TOKIO_CONSOLE_RECORD_PATH`         | The file path to save a recording                                         | None              |
654/// | `RUST_LOG`                          | Configures what events are logged events. See [`Targets`] for details.    | "error"           |
655///
656/// If the "env-filter" crate feature flag is enabled, the `RUST_LOG`
657/// environment variable will be parsed using the [`EnvFilter`] type from
658/// `tracing-subscriber. If the "env-filter" feature is **not** enabled, the
659/// [`Targets`] filter is used instead. The `EnvFilter` type accepts all the
660/// same syntax as `Targets`, but with the added ability to filter dynamically
661/// on span field values. See the documentation for those types for details.
662///
663/// # Further customization
664///
665/// To add additional layers or replace the format layer, replace
666/// `hds_console_subscriber::init` with:
667///
668/// ```rust
669/// use tracing_subscriber::prelude::*;
670///
671/// let console_layer = hds_console_subscriber::spawn();
672///
673/// tracing_subscriber::registry()
674///     .with(console_layer)
675///     .with(tracing_subscriber::fmt::layer())
676/// //  .with(..potential additional layer..)
677///     .init();
678/// ```
679///
680/// Calling `hds_console_subscriber::init` is equivalent to the following:
681/// ```rust
682/// use hds_console_subscriber::ConsoleLayer;
683///
684/// ConsoleLayer::builder().with_default_env().init();
685/// ```
686///
687/// [`Targets`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/filter/struct.Targets.html
688/// [`EnvFilter`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/filter/struct.EnvFilter.html
689pub fn init() {
690    ConsoleLayer::builder().with_default_env().init();
691}
692
693/// Returns a new `tracing_subscriber` [`Layer`] configured with a [`ConsoleLayer`]
694/// and a [filter] that enables the spans and events required by the console.
695///
696/// This function spawns the console subscriber's [`Server`] in its own Tokio
697/// runtime in a background thread.
698///
699/// Unlike [`init`], this function does not set the default subscriber, allowing
700/// additional [`Layer`]s to be added.
701///
702/// This function is equivalent to the following:
703/// ```
704/// use hds_console_subscriber::ConsoleLayer;
705///
706/// let layer = ConsoleLayer::builder().with_default_env().spawn();
707/// # use tracing_subscriber::prelude::*;
708/// # tracing_subscriber::registry().with(layer).init(); // to suppress must_use warnings
709/// ```
710/// [filter]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/targets/struct.Targets.html
711/// [`Layer`]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/trait.Layer.html
712/// [`Server`]: crate::Server
713///
714/// # Panics
715///
716/// * If the subscriber's background thread could not be spawned.
717///
718/// # Configuration
719///
720/// `hds_console_subscriber::build` supports all of the environmental
721/// configuration described at [`hds_console_subscriber::init`].
722///
723/// # Differences from `init`
724///
725/// Unlike [`hds_console_subscriber::init`], this function does *not* add a
726/// [`tracing_subscriber::fmt`] layer to the configured `Layer`. This means
727/// that this function will not log spans and events based on the value of the
728/// `RUST_LOG` environment variable. Instead, a user-provided [`fmt::Layer`] can
729/// be added in order to customize the log format.
730///
731/// You must call [`.init()`] on the final subscriber in order to [set the
732/// subscriber as the default][default].
733///
734/// # Examples
735///
736/// ```rust
737/// use tracing_subscriber::prelude::*;
738/// tracing_subscriber::registry()
739///     .with(hds_console_subscriber::spawn())
740///     .with(tracing_subscriber::fmt::layer())
741/// //  .with(...)
742///     .init();
743/// ```
744/// [`.init()`]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/util/trait.SubscriberInitExt.html
745/// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber
746/// [sub]: https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
747/// [`tracing_subscriber::fmt`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/fmt/index.html
748/// [`fmt::Layer`]: https://docs.rs/tracing-subscriber/latest/tracing-subscriber/fmt/struct.Layer.html
749/// [`hds_console_subscriber::init`]: crate::init()
750#[must_use = "a `Layer` must be added to a `tracing::Subscriber`in order to be used"]
751pub fn spawn<S>() -> impl Layer<S>
752where
753    S: Subscriber + for<'a> LookupSpan<'a>,
754{
755    ConsoleLayer::builder().with_default_env().spawn::<S>()
756}
757
758fn duration_from_env(var_name: &str) -> Option<Duration> {
759    let var = std::env::var(var_name).ok()?;
760    match var.parse::<humantime::Duration>() {
761        Ok(dur) => Some(dur.into()),
762        Err(e) => panic!(
763            "failed to parse a duration from `{}={:?}`: {}",
764            var_name, var, e
765        ),
766    }
767}