Skip to main content

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        strict_provenance_lints,
133        unqualified_local_imports,
134    )
135)]
136#![cfg_attr(nightly, allow(single_use_lifetimes))]
137#![cfg_attr(
138    nightly,
139    deny(
140        absolute_paths_not_starting_with_crate,
141        ambiguous_glob_imports,
142        ambiguous_glob_reexports,
143        ambiguous_negative_literals,
144        ambiguous_wide_pointer_comparisons,
145        anonymous_parameters,
146        array_into_iter,
147        asm_sub_register,
148        async_fn_in_trait,
149        bad_asm_style,
150        bare_trait_objects,
151        boxed_slice_into_iter,
152        break_with_label_and_loop,
153        clashing_extern_declarations,
154        closure_returning_async_block,
155        coherence_leak_check,
156        confusable_idents,
157        const_evaluatable_unchecked,
158        const_item_mutation,
159        dangling_pointers_from_temporaries,
160        dead_code,
161        dependency_on_unit_never_type_fallback,
162        deprecated,
163        deprecated_in_future,
164        deprecated_safe_2024,
165        deprecated_where_clause_location,
166        deref_into_dyn_supertrait,
167        deref_nullptr,
168        double_negations,
169        drop_bounds,
170        dropping_copy_types,
171        dropping_references,
172        duplicate_macro_attributes,
173        dyn_drop,
174        edition_2024_expr_fragment_specifier,
175        elided_lifetimes_in_paths,
176        ellipsis_inclusive_range_patterns,
177        explicit_outlives_requirements,
178        exported_private_dependencies,
179        ffi_unwind_calls,
180        forbidden_lint_groups,
181        forgetting_copy_types,
182        forgetting_references,
183        for_loops_over_fallibles,
184        function_item_references,
185        hidden_glob_reexports,
186        if_let_rescope,
187        impl_trait_overcaptures,
188        impl_trait_redundant_captures,
189        improper_ctypes,
190        improper_ctypes_definitions,
191        inline_no_sanitize,
192        internal_features,
193        invalid_from_utf8,
194        invalid_macro_export_arguments,
195        invalid_nan_comparisons,
196        invalid_value,
197        irrefutable_let_patterns,
198        keyword_idents_2018,
199        keyword_idents_2024,
200        large_assignments,
201        late_bound_lifetime_arguments,
202        legacy_derive_helpers,
203        let_underscore_drop,
204        macro_use_extern_crate,
205        map_unit_fn,
206        meta_variable_misuse,
207        mismatched_lifetime_syntaxes,
208        missing_abi,
209        missing_copy_implementations,
210        missing_debug_implementations,
211        missing_docs,
212        missing_unsafe_on_extern,
213        mixed_script_confusables,
214        named_arguments_used_positionally,
215        never_type_fallback_flowing_into_unsafe,
216        non_ascii_idents,
217        non_camel_case_types,
218        non_contiguous_range_endpoints,
219        non_fmt_panics,
220        non_local_definitions,
221        non_shorthand_field_patterns,
222        non_snake_case,
223        non_upper_case_globals,
224        noop_method_call,
225        opaque_hidden_inferred_bound,
226        out_of_scope_macro_calls,
227        overlapping_range_endpoints,
228        path_statements,
229        private_bounds,
230        private_interfaces,
231        ptr_to_integer_transmute_in_consts,
232        redundant_imports,
233        redundant_lifetimes,
234        redundant_semicolons,
235        refining_impl_trait_internal,
236        refining_impl_trait_reachable,
237        renamed_and_removed_lints,
238        rust_2021_incompatible_closure_captures,
239        rust_2021_incompatible_or_patterns,
240        rust_2021_prefixes_incompatible_syntax,
241        rust_2021_prelude_collisions,
242        rust_2024_guarded_string_incompatible_syntax,
243        rust_2024_incompatible_pat,
244        rust_2024_prelude_collisions,
245        self_constructor_from_outer_item,
246        semicolon_in_expressions_from_macros,
247        single_use_lifetimes,
248        special_module_name,
249        stable_features,
250        static_mut_refs,
251        suspicious_double_ref_op,
252        tail_expr_drop_order,
253        trivial_bounds,
254        trivial_casts,
255        trivial_numeric_casts,
256        type_alias_bounds,
257        tyvar_behind_raw_pointer,
258        uncommon_codepoints,
259        unconditional_recursion,
260        uncovered_param_in_projection,
261        unexpected_cfgs,
262        unfulfilled_lint_expectations,
263        ungated_async_fn_track_caller,
264        uninhabited_static,
265        unit_bindings,
266        unknown_lints,
267        unknown_or_malformed_diagnostic_attributes,
268        unnameable_test_items,
269        unnameable_types,
270        unpredictable_function_pointer_comparisons,
271        unreachable_code,
272        unreachable_patterns,
273        unreachable_pub,
274        unsafe_attr_outside_unsafe,
275        unsafe_code,
276        unsafe_op_in_unsafe_fn,
277        unstable_name_collisions,
278        unstable_syntax_pre_expansion,
279        unused_allocation,
280        unused_assignments,
281        unused_associated_type_bounds,
282        unused_attributes,
283        unused_braces,
284        unused_comparisons,
285        unused_crate_dependencies,
286        unused_doc_comments,
287        unused_extern_crates,
288        unused_features,
289        unused_import_braces,
290        unused_imports,
291        unused_labels,
292        unused_lifetimes,
293        unused_macro_rules,
294        unused_macros,
295        unused_must_use,
296        unused_mut,
297        unused_parens,
298        unused_qualifications,
299        unused_results,
300        unused_unsafe,
301        unused_variables,
302        useless_ptr_null_checks,
303        uses_power_alignment,
304        variant_size_differences,
305        while_true,
306    )
307)]
308// If nightly and unstable, allow `incomplete_features` and `unstable_features`
309#![cfg_attr(
310    all(feature = "unstable", nightly),
311    allow(incomplete_features, unstable_features)
312)]
313// If nightly and not unstable, deny `incomplete_features` and `unstable_features`
314#![cfg_attr(
315    all(not(feature = "unstable"), nightly),
316    deny(incomplete_features, unstable_features)
317)]
318// The unstable lints
319#![cfg_attr(
320    all(feature = "unstable", nightly),
321    deny(
322        implicit_provenance_casts,
323        multiple_supertrait_upcastable,
324        must_not_suspend,
325        non_exhaustive_omitted_patterns,
326        unqualified_local_imports,
327    )
328)]
329// clippy lints
330#![cfg_attr(nightly, deny(clippy::all, clippy::pedantic))]
331// rustdoc lints
332#![cfg_attr(
333    nightly,
334    deny(
335        rustdoc::bare_urls,
336        rustdoc::broken_intra_doc_links,
337        rustdoc::invalid_codeblock_attributes,
338        rustdoc::invalid_html_tags,
339        rustdoc::missing_crate_level_docs,
340        rustdoc::private_doc_tests,
341        rustdoc::private_intra_doc_links,
342    )
343)]
344#![cfg_attr(all(docsrs, nightly), feature(doc_cfg))]
345
346mod config;
347mod format;
348mod initialize;
349mod utils;
350
351pub use self::config::Config as TracingConfig;
352pub use self::format::compact::compact;
353pub use self::format::compact::filtered as compact_filtered;
354pub use self::format::full::filtered as full_filtered;
355pub use self::format::full::full;
356#[cfg(feature = "json")]
357pub use self::format::json::filtered as json_filtered;
358#[cfg(feature = "json")]
359pub use self::format::json::json;
360pub use self::format::pretty::filtered as pretty_filtered;
361pub use self::format::pretty::pretty;
362pub use self::initialize::init;
363pub use self::initialize::set_default;
364pub use self::initialize::try_init;
365pub use self::utils::TestAll;
366pub use self::utils::get_effective_level;
367
368#[cfg(feature = "time")]
369#[doc(no_inline)]
370pub use time::format_description::well_known::Iso8601;
371#[cfg(feature = "time")]
372#[doc(no_inline)]
373pub use time::format_description::well_known::Rfc2822;
374#[cfg(feature = "time")]
375#[doc(no_inline)]
376pub use time::format_description::well_known::Rfc3339;
377#[cfg(feature = "tstime")]
378#[doc(no_inline)]
379pub use tracing_subscriber::Layer;
380#[cfg(feature = "tstime")]
381#[doc(no_inline)]
382pub use tracing_subscriber::fmt::time::OffsetTime;
383#[cfg(feature = "tstime")]
384#[doc(no_inline)]
385pub use tracing_subscriber::fmt::time::SystemTime;
386#[cfg(feature = "tstime")]
387#[doc(no_inline)]
388pub use tracing_subscriber::fmt::time::Uptime;
389#[cfg(feature = "tstime")]
390#[doc(no_inline)]
391pub use tracing_subscriber::fmt::time::UtcTime;