tracing_subscriber_init/
lib.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
9//! Convenience trait and functions to ease [`tracing-subscriber`][tracing-subscriber] initialization.
10//!
11//! Program configuration can come from multiple sources. This crate supplies the [`TracingConfig`] trait to allow the grouping
12//! of [`tracing-subscriber`][tracing-subscriber] initialization related items.
13//!
14//! For example, I often have some configuration from the command line (quiet and verbose flags),
15//! some configuration from a configuration file, and some configuration (secrets) loaded from external sources.  I implement this
16//! trait on a struct to collect the [`tracing-subscriber`][tracing-subscriber] related configuration, then use functions such as
17//! [`full_filtered`](crate::full_filtered) to configure layers as appropriate.
18//!
19//! There are also convenience functions such as [`set_default`](crate::set_default) that will
20//! setup a [`Registry`](tracing_subscriber::registry::Registry), add the given vector of [`Layer`](tracing_subscriber::Layer),
21//! and initialize per the upstream functions of the
22//! [same name](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/util/trait.SubscriberInitExt.html#method.set_default).
23//!
24//! [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/
25//! # Example
26//! ```rust
27//! # use anyhow::Result;
28//! # use std::fs::File;
29//! # use tracing::{info, Level, span};
30//! # use tracing_subscriber::{Layer, fmt::format::FmtSpan};
31//! # use tracing_subscriber_init::{TracingConfig, full, full_filtered, set_default};
32//! #
33//! # pub fn main() -> Result<()> {
34//! #[derive(Clone, Debug, Default)]
35//! struct TomlConfig {
36//!     // ...other configuration
37//!     tracing: Tracing,
38//!     tracing_file: TracingFile,
39//!     // ...other configuration
40//! }
41//!
42//! #[derive(Clone, Debug, Default)]
43//! struct Tracing {
44//!     target: bool,
45//!     thread_ids: bool,
46//!     thread_names: bool,
47//!     line_numbers: bool,
48//! }
49//!
50//! impl TracingConfig for Tracing {
51//!     // Normally pulled from command line arguments, i.e. prog -qq
52//!     fn quiet(&self) -> u8 {
53//!         0
54//!     }
55//!
56//!     // Normally pulled from command line arguments, i.e. prog -vv
57//!     fn verbose(&self) -> u8 {
58//!         2
59//!     }
60//!
61//!     fn with_line_number(&self) -> bool {
62//!         self.line_numbers
63//!     }
64//!
65//!     fn with_target(&self) -> bool {
66//!         self.target
67//!     }
68//!
69//!     fn with_thread_ids(&self) -> bool {
70//!         self.thread_ids
71//!     }
72//!
73//!     fn with_thread_names(&self) -> bool {
74//!         self.thread_names
75//!     }
76//! }
77//!
78//! #[derive(Clone, Debug, Default)]
79//! struct TracingFile;
80//!
81//! impl TracingConfig for TracingFile {
82//!     fn quiet(&self) -> u8 {
83//!         0
84//!     }
85//!
86//!     fn verbose(&self) -> u8 {
87//!         3
88//!     }
89//!
90//!     fn with_ansi(&self) -> bool {
91//!         false
92//!     }
93//! }
94//!
95//! // Load configuration and pull out the tracing specific.
96//! let toml_config = TomlConfig::default();
97//! let tracing_config = toml_config.tracing;
98//! let tracing_file_config = toml_config.tracing_file;
99//!
100//! // Setup a full format, filtered layer.  The filtering is set based on the quiet
101//! // and verbose values from the configuration
102//! let layer = full_filtered(&tracing_config);
103//!
104//! // Setup a second full format layer to write to a file.  Use the non-filtered
105//! // version when you wish to modify items such as the writer, or the time format.
106//! // You can also chose to ignore the generated level filter and apply your own.
107//! let file = File::create("trace.log")?;
108//! let (file_layer, level_filter) = full(&tracing_file_config);
109//! let file_layer = file_layer.with_writer(file).with_filter(level_filter);
110//!
111//! // Create a Registry, add the layers, and set this subscriber as the default
112//! // for this scope
113//! let _unused = set_default(vec![layer.boxed(), file_layer.boxed()]);
114//!
115//! // Create a new span and enter it.
116//! let span = span!(Level::INFO, "a new span");
117//! let _enter = span.enter();
118//!
119//! // Trace away...
120//! info!("info level");
121//! #    Ok(())
122//! # }
123//! ```
124
125// rustc lints
126#![cfg_attr(
127    all(feature = "unstable", nightly),
128    feature(
129        multiple_supertrait_upcastable,
130        must_not_suspend,
131        non_exhaustive_omitted_patterns_lint,
132        rustdoc_missing_doc_code_examples,
133        strict_provenance_lints,
134        supertrait_item_shadowing,
135        unqualified_local_imports,
136    )
137)]
138#![cfg_attr(nightly, allow(single_use_lifetimes))]
139#![cfg_attr(
140    nightly,
141    deny(
142        absolute_paths_not_starting_with_crate,
143        ambiguous_glob_imports,
144        ambiguous_glob_reexports,
145        ambiguous_negative_literals,
146        ambiguous_wide_pointer_comparisons,
147        anonymous_parameters,
148        array_into_iter,
149        asm_sub_register,
150        async_fn_in_trait,
151        bad_asm_style,
152        bare_trait_objects,
153        boxed_slice_into_iter,
154        break_with_label_and_loop,
155        clashing_extern_declarations,
156        closure_returning_async_block,
157        coherence_leak_check,
158        confusable_idents,
159        const_evaluatable_unchecked,
160        const_item_mutation,
161        dangling_pointers_from_temporaries,
162        dead_code,
163        dependency_on_unit_never_type_fallback,
164        deprecated,
165        deprecated_in_future,
166        deprecated_safe_2024,
167        deprecated_where_clause_location,
168        deref_into_dyn_supertrait,
169        deref_nullptr,
170        double_negations,
171        drop_bounds,
172        dropping_copy_types,
173        dropping_references,
174        duplicate_macro_attributes,
175        dyn_drop,
176        edition_2024_expr_fragment_specifier,
177        elided_lifetimes_in_paths,
178        ellipsis_inclusive_range_patterns,
179        explicit_outlives_requirements,
180        exported_private_dependencies,
181        ffi_unwind_calls,
182        forbidden_lint_groups,
183        forgetting_copy_types,
184        forgetting_references,
185        for_loops_over_fallibles,
186        function_item_references,
187        hidden_glob_reexports,
188        if_let_rescope,
189        impl_trait_overcaptures,
190        impl_trait_redundant_captures,
191        improper_ctypes,
192        improper_ctypes_definitions,
193        inline_no_sanitize,
194        internal_features,
195        invalid_from_utf8,
196        invalid_macro_export_arguments,
197        invalid_nan_comparisons,
198        invalid_value,
199        irrefutable_let_patterns,
200        keyword_idents_2018,
201        keyword_idents_2024,
202        large_assignments,
203        late_bound_lifetime_arguments,
204        legacy_derive_helpers,
205        let_underscore_drop,
206        macro_use_extern_crate,
207        map_unit_fn,
208        meta_variable_misuse,
209        mismatched_lifetime_syntaxes,
210        missing_abi,
211        missing_copy_implementations,
212        missing_debug_implementations,
213        missing_docs,
214        missing_unsafe_on_extern,
215        mixed_script_confusables,
216        named_arguments_used_positionally,
217        never_type_fallback_flowing_into_unsafe,
218        no_mangle_generic_items,
219        non_ascii_idents,
220        non_camel_case_types,
221        non_contiguous_range_endpoints,
222        non_fmt_panics,
223        non_local_definitions,
224        non_shorthand_field_patterns,
225        non_snake_case,
226        non_upper_case_globals,
227        noop_method_call,
228        opaque_hidden_inferred_bound,
229        out_of_scope_macro_calls,
230        overlapping_range_endpoints,
231        path_statements,
232        private_bounds,
233        private_interfaces,
234        ptr_to_integer_transmute_in_consts,
235        redundant_imports,
236        redundant_lifetimes,
237        redundant_semicolons,
238        refining_impl_trait_internal,
239        refining_impl_trait_reachable,
240        renamed_and_removed_lints,
241        repr_transparent_external_private_fields,
242        rust_2021_incompatible_closure_captures,
243        rust_2021_incompatible_or_patterns,
244        rust_2021_prefixes_incompatible_syntax,
245        rust_2021_prelude_collisions,
246        rust_2024_guarded_string_incompatible_syntax,
247        rust_2024_incompatible_pat,
248        rust_2024_prelude_collisions,
249        self_constructor_from_outer_item,
250        semicolon_in_expressions_from_macros,
251        single_use_lifetimes,
252        special_module_name,
253        stable_features,
254        static_mut_refs,
255        suspicious_double_ref_op,
256        tail_expr_drop_order,
257        trivial_bounds,
258        trivial_casts,
259        trivial_numeric_casts,
260        type_alias_bounds,
261        tyvar_behind_raw_pointer,
262        uncommon_codepoints,
263        unconditional_recursion,
264        uncovered_param_in_projection,
265        unexpected_cfgs,
266        unfulfilled_lint_expectations,
267        ungated_async_fn_track_caller,
268        uninhabited_static,
269        unit_bindings,
270        unknown_lints,
271        unknown_or_malformed_diagnostic_attributes,
272        unnameable_test_items,
273        unnameable_types,
274        unpredictable_function_pointer_comparisons,
275        unreachable_code,
276        unreachable_patterns,
277        unreachable_pub,
278        unsafe_attr_outside_unsafe,
279        unsafe_code,
280        unsafe_op_in_unsafe_fn,
281        unstable_name_collisions,
282        unstable_syntax_pre_expansion,
283        unused_allocation,
284        unused_assignments,
285        unused_associated_type_bounds,
286        unused_attributes,
287        unused_braces,
288        unused_comparisons,
289        unused_crate_dependencies,
290        unused_doc_comments,
291        unused_extern_crates,
292        unused_features,
293        unused_import_braces,
294        unused_imports,
295        unused_labels,
296        unused_lifetimes,
297        unused_macro_rules,
298        unused_macros,
299        unused_must_use,
300        unused_mut,
301        unused_parens,
302        unused_qualifications,
303        unused_results,
304        unused_unsafe,
305        unused_variables,
306        useless_ptr_null_checks,
307        uses_power_alignment,
308        variant_size_differences,
309        while_true,
310    )
311)]
312// If nightly and unstable, allow `incomplete_features` and `unstable_features`
313#![cfg_attr(
314    all(feature = "unstable", nightly),
315    allow(incomplete_features, unstable_features)
316)]
317// If nightly and not unstable, deny `incomplete_features` and `unstable_features`
318#![cfg_attr(
319    all(not(feature = "unstable"), nightly),
320    deny(incomplete_features, unstable_features)
321)]
322// The unstable lints
323#![cfg_attr(
324    all(feature = "unstable", nightly),
325    deny(
326        fuzzy_provenance_casts,
327        lossy_provenance_casts,
328        multiple_supertrait_upcastable,
329        must_not_suspend,
330        non_exhaustive_omitted_patterns,
331        supertrait_item_shadowing_definition,
332        supertrait_item_shadowing_usage,
333        unqualified_local_imports,
334    )
335)]
336// clippy lints
337#![cfg_attr(nightly, deny(clippy::all, clippy::pedantic))]
338// rustdoc lints
339#![cfg_attr(
340    nightly,
341    deny(
342        rustdoc::bare_urls,
343        rustdoc::broken_intra_doc_links,
344        rustdoc::invalid_codeblock_attributes,
345        rustdoc::invalid_html_tags,
346        rustdoc::missing_crate_level_docs,
347        rustdoc::private_doc_tests,
348        rustdoc::private_intra_doc_links,
349    )
350)]
351#![cfg_attr(
352    all(nightly, feature = "unstable"),
353    deny(rustdoc::missing_doc_code_examples)
354)]
355#![cfg_attr(all(docsrs, nightly), feature(doc_cfg))]
356
357mod config;
358mod format;
359mod initialize;
360mod utils;
361
362pub use self::config::Config as TracingConfig;
363pub use self::format::compact::compact;
364pub use self::format::compact::filtered as compact_filtered;
365pub use self::format::full::filtered as full_filtered;
366pub use self::format::full::full;
367#[cfg(feature = "json")]
368pub use self::format::json::filtered as json_filtered;
369#[cfg(feature = "json")]
370pub use self::format::json::json;
371pub use self::format::pretty::filtered as pretty_filtered;
372pub use self::format::pretty::pretty;
373pub use self::initialize::init;
374pub use self::initialize::set_default;
375pub use self::initialize::try_init;
376pub use self::utils::TestAll;
377pub use self::utils::get_effective_level;
378
379#[cfg(feature = "time")]
380#[doc(no_inline)]
381pub use time::format_description::well_known::Iso8601;
382#[cfg(feature = "time")]
383#[doc(no_inline)]
384pub use time::format_description::well_known::Rfc2822;
385#[cfg(feature = "time")]
386#[doc(no_inline)]
387pub use time::format_description::well_known::Rfc3339;
388#[cfg(feature = "tstime")]
389#[doc(no_inline)]
390pub use tracing_subscriber::Layer;
391#[cfg(feature = "tstime")]
392#[doc(no_inline)]
393pub use tracing_subscriber::fmt::time::OffsetTime;
394#[cfg(feature = "tstime")]
395#[doc(no_inline)]
396pub use tracing_subscriber::fmt::time::SystemTime;
397#[cfg(feature = "tstime")]
398#[doc(no_inline)]
399pub use tracing_subscriber::fmt::time::Uptime;
400#[cfg(feature = "tstime")]
401#[doc(no_inline)]
402pub use tracing_subscriber::fmt::time::UtcTime;