tracing/lib.rs
1//! A scoped, structured logging and diagnostics system.
2//!
3//! # Overview
4//!
5//! `tracing` is a framework for instrumenting Rust programs to collect
6//! structured, event-based diagnostic information.
7//!
8//! In asynchronous systems like Tokio, interpreting traditional log messages can
9//! often be quite challenging. Since individual tasks are multiplexed on the same
10//! thread, associated events and log lines are intermixed making it difficult to
11//! trace the logic flow. `tracing` expands upon logging-style diagnostics by
12//! allowing libraries and applications to record structured events with additional
13//! information about *temporality* and *causality* — unlike a log message, a span
14//! in `tracing` has a beginning and end time, may be entered and exited by the
15//! flow of execution, and may exist within a nested tree of similar spans. In
16//! addition, `tracing` spans are *structured*, with the ability to record typed
17//! data as well as textual messages.
18//!
19//! The `tracing` crate provides the APIs necessary for instrumenting libraries
20//! and applications to emit trace data.
21//!
22//! *Compiler support: [requires `rustc` 1.65+][msrv]*
23//!
24//! [msrv]: #supported-rust-versions
25//! # Core Concepts
26//!
27//! The core of `tracing`'s API is composed of _spans_, _events_ and
28//! _collectors_. We'll cover these in turn.
29//!
30//! ## Spans
31//!
32//! To record the flow of execution through a program, `tracing` introduces the
33//! concept of [spans]. Unlike a log line that represents a _moment in
34//! time_, a span represents a _period of time_ with a beginning and an end. When a
35//! program begins executing in a context or performing a unit of work, it
36//! _enters_ that context's span, and when it stops executing in that context,
37//! it _exits_ the span. The span in which a thread is currently executing is
38//! referred to as that thread's _current_ span.
39//!
40//! For example:
41//! ```
42//! use tracing::{span, Level};
43//! # fn main() {
44//! let span = span!(Level::TRACE, "my_span");
45//! // `enter` returns a RAII guard which, when dropped, exits the span. this
46//! // indicates that we are in the span for the current lexical scope.
47//! let _enter = span.enter();
48//! // perform some work in the context of `my_span`...
49//! # }
50//!```
51//!
52//! The [`span` module][mod@span]'s documentation provides further details on how to
53//! use spans.
54//!
55//! <div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
56//!
57//! **Warning**: In asynchronous code that uses async/await syntax,
58//! `Span::enter` may produce incorrect traces if the returned drop
59//! guard is held across an await point. See
60//! [the method documentation][Span#in-asynchronous-code] for details.
61//!
62//! </pre></div>
63//!
64//! ## Events
65//!
66//! An [`Event`] represents a _moment_ in time. It signifies something that
67//! happened while a trace was being recorded. `Event`s are comparable to the log
68//! records emitted by unstructured logging code, but unlike a typical log line,
69//! an `Event` may occur within the context of a span.
70//!
71//! For example:
72//! ```
73//! use tracing::{event, span, Level};
74//!
75//! # fn main() {
76//! // records an event outside of any span context:
77//! event!(Level::INFO, "something happened");
78//!
79//! let span = span!(Level::INFO, "my_span");
80//! let _guard = span.enter();
81//!
82//! // records an event within "my_span".
83//! event!(Level::DEBUG, "something happened inside my_span");
84//! # }
85//!```
86//!
87//! In general, events should be used to represent points in time _within_ a
88//! span — a request returned with a given status code, _n_ new items were
89//! taken from a queue, and so on.
90//!
91//! The [`Event` struct][`Event`] documentation provides further details on using
92//! events.
93//!
94//! ## Collectors
95//!
96//! As `Span`s and `Event`s occur, they are recorded or aggregated by
97//! implementations of the [`Collect`] trait. Collectors are notified
98//! when an `Event` takes place and when a `Span` is entered or exited. These
99//! notifications are represented by the following `Collect` trait methods:
100//!
101//! + [`event`][Collect::event], called when an `Event` takes place,
102//! + [`enter`], called when execution enters a `Span`,
103//! + [`exit`], called when execution exits a `Span`
104//!
105//! In addition, collectors may implement the [`enabled`] function to _filter_
106//! the notifications they receive based on [metadata] describing each `Span`
107//! or `Event`. If a call to `Collect::enabled` returns `false` for a given
108//! set of metadata, that collector will *not* be notified about the
109//! corresponding `Span` or `Event`. For performance reasons, if no currently
110//! active collectors express interest in a given set of metadata by returning
111//! `true`, then the corresponding `Span` or `Event` will never be constructed.
112//!
113//! # Usage
114//!
115//! First, add this to your `Cargo.toml`:
116//!
117//! ```toml
118//! [dependencies]
119//! tracing = "0.1"
120//! ```
121//!
122//! ## Recording Spans and Events
123//!
124//! Spans and events are recorded using macros.
125//!
126//! ### Spans
127//!
128//! The [`span!`] macro expands to a [`Span` struct][`Span`] which is used to
129//! record a span. The [`Span::enter`] method on that struct records that the
130//! span has been entered, and returns a [RAII] guard object, which will exit
131//! the span when dropped.
132//!
133//! For example:
134//!
135//! ```rust
136//! use tracing::{span, Level};
137//! # fn main() {
138//! // Construct a new span named "my span" with trace log level.
139//! let span = span!(Level::TRACE, "my span");
140//!
141//! // Enter the span, returning a guard object.
142//! let _enter = span.enter();
143//!
144//! // Any trace events that occur before the guard is dropped will occur
145//! // within the span.
146//!
147//! // Dropping the guard will exit the span.
148//! # }
149//! ```
150//!
151//! The [`#[instrument]`][instrument] attribute provides an easy way to
152//! add `tracing` spans to functions. A function annotated with `#[instrument]`
153//! will create and enter a span with that function's name every time the
154//! function is called, with arguments to that function will be recorded as
155//! fields using `fmt::Debug`.
156//!
157//! For example:
158//! ```ignore
159//! # // this doctest is ignored because we don't have a way to say
160//! # // that it should only be run with cfg(feature = "attributes")
161//! use tracing::{Level, event, instrument};
162//!
163//! #[instrument]
164//! pub fn my_function(my_arg: usize) {
165//! // This event will be recorded inside a span named `my_function` with the
166//! // field `my_arg`.
167//! event!(Level::INFO, "inside my_function!");
168//! // ...
169//! }
170//! # fn main() {}
171//! ```
172//!
173//! For functions which don't have built-in tracing support and can't have
174//! the `#[instrument]` attribute applied (such as from an external crate),
175//! the [`Span` struct][`Span`] has a [`in_scope()` method][`in_scope`]
176//! which can be used to easily wrap synchronous code in a span.
177//!
178//! For example:
179//! ```rust
180//! use tracing::info_span;
181//!
182//! # fn doc() -> Result<(), ()> {
183//! # mod serde_json {
184//! # pub(crate) fn from_slice(buf: &[u8]) -> Result<(), ()> { Ok(()) }
185//! # }
186//! # let buf: [u8; 0] = [];
187//! let json = info_span!("json.parse").in_scope(|| serde_json::from_slice(&buf))?;
188//! # let _ = json; // suppress unused variable warning
189//! # Ok(())
190//! # }
191//! ```
192//!
193//! You can find more examples showing how to use this crate [here][examples].
194//!
195//! [RAII]: https://github.com/rust-unofficial/patterns/blob/main/src/patterns/behavioural/RAII.md
196//! [examples]: https://github.com/tokio-rs/tracing/tree/master/examples
197//!
198//! ### Events
199//!
200//! [`Event`]s are recorded using the [`event!`] macro:
201//!
202//! ```rust
203//! # fn main() {
204//! use tracing::{event, Level};
205//! event!(Level::INFO, "something has happened!");
206//! # }
207//! ```
208//!
209//! ## Using the Macros
210//!
211//! The [`span!`] and [`event!`] macros use fairly similar syntax, with some
212//! exceptions.
213//!
214//! ### Configuring Attributes
215//!
216//! Both macros require a [`Level`] specifying the verbosity of the span or
217//! event. Optionally, the, [target] and [parent span] may be overridden. If the
218//! target and parent span are not overridden, they will default to the
219//! module path where the macro was invoked and the current span (as determined
220//! by the collector), respectively.
221//!
222//! For example:
223//!
224//! ```
225//! # use tracing::{span, event, Level};
226//! # fn main() {
227//! span!(target: "app_spans", Level::TRACE, "my span");
228//! event!(target: "app_events", Level::INFO, "something has happened!");
229//! # }
230//! ```
231//! ```
232//! # use tracing::{span, event, Level};
233//! # fn main() {
234//! let span = span!(Level::TRACE, "my span");
235//! event!(parent: &span, Level::INFO, "something has happened!");
236//! # }
237//! ```
238//!
239//! The span macros also take a string literal after the level, to set the name
240//! of the span (as above). In the case of the event macros, the name of the event can
241//! be overridden (the default is `event file:line`) using the `name:` specifier.
242//!
243//! ```
244//! # use tracing::{span, event, Level};
245//! # fn main() {
246//! span!(Level::TRACE, "my span");
247//! event!(name: "some_info", Level::INFO, "something has happened!");
248//! # }
249//! ```
250//!
251//! ### Recording Fields
252//!
253//! Structured fields on spans and events are specified using the syntax
254//! `field_name = field_value`. Fields are separated by commas.
255//!
256//! ```
257//! # use tracing::{event, Level};
258//! # fn main() {
259//! // records an event with two fields:
260//! // - "answer", with the value 42
261//! // - "question", with the value "life, the universe and everything"
262//! event!(Level::INFO, answer = 42, question = "life, the universe, and everything");
263//! # }
264//! ```
265//!
266//! As shorthand, local variables may be used as field values without an
267//! assignment, similar to [struct initializers]. For example:
268//!
269//! ```
270//! # use tracing::{span, Level};
271//! # fn main() {
272//! let user = "ferris";
273//!
274//! span!(Level::TRACE, "login", user);
275//! // is equivalent to:
276//! span!(Level::TRACE, "login", user = user);
277//! # }
278//!```
279//!
280//! Field names can include dots, but should not be terminated by them:
281//! ```
282//! # use tracing::{span, Level};
283//! # fn main() {
284//! let user = "ferris";
285//! let email = "ferris@rust-lang.org";
286//! span!(Level::TRACE, "login", user, user.email = email);
287//! # }
288//!```
289//!
290//! Since field names can include dots, fields on local structs can be used
291//! using the local variable shorthand:
292//! ```
293//! # use tracing::{span, Level};
294//! # fn main() {
295//! # struct User {
296//! # name: &'static str,
297//! # email: &'static str,
298//! # }
299//! let user = User {
300//! name: "ferris",
301//! email: "ferris@rust-lang.org",
302//! };
303//! // the span will have the fields `user.name = "ferris"` and
304//! // `user.email = "ferris@rust-lang.org"`.
305//! span!(Level::TRACE, "login", user.name, user.email);
306//! # }
307//!```
308//!
309//! Fields with names that are not Rust identifiers, or with names that are Rust reserved words,
310//! may be created using quoted string literals. However, this may not be used with the local
311//! variable shorthand.
312//! ```
313//! # use tracing::{span, Level};
314//! # fn main() {
315//! // records an event with fields whose names are not Rust identifiers
316//! // - "guid:x-request-id", containing a `:`, with the value "abcdef"
317//! // - "type", which is a reserved word, with the value "request"
318//! span!(Level::TRACE, "api", "guid:x-request-id" = "abcdef", "type" = "request");
319//! # }
320//!```
321//!
322//! Constant expressions can also be used as field names. Constants
323//! must be enclosed in curly braces (`{}`) to indicate that the *value*
324//! of the constant is to be used as the field name, rather than the
325//! constant's name. For example:
326//! ```
327//! # use tracing::{span, Level};
328//! # fn main() {
329//! const RESOURCE_NAME: &str = "foo";
330//! // this span will have the field `foo = "some_id"`
331//! span!(Level::TRACE, "get", { RESOURCE_NAME } = "some_id");
332//! # }
333//!```
334//!
335//! The `?` sigil is shorthand that specifies a field should be recorded using
336//! its [`fmt::Debug`] implementation:
337//! ```
338//! # use tracing::{event, Level};
339//! # fn main() {
340//! #[derive(Debug)]
341//! struct MyStruct {
342//! field: &'static str,
343//! }
344//!
345//! let my_struct = MyStruct {
346//! field: "Hello world!"
347//! };
348//!
349//! // `my_struct` will be recorded using its `fmt::Debug` implementation.
350//! event!(Level::TRACE, greeting = ?my_struct);
351//! // is equivalent to:
352//! event!(Level::TRACE, greeting = tracing::field::debug(&my_struct));
353//! # }
354//! ```
355//!
356//! The `%` sigil operates similarly, but indicates that the value should be
357//! recorded using its [`fmt::Display`] implementation:
358//! ```
359//! # use tracing::{event, Level};
360//! # fn main() {
361//! # #[derive(Debug)]
362//! # struct MyStruct {
363//! # field: &'static str,
364//! # }
365//! #
366//! # let my_struct = MyStruct {
367//! # field: "Hello world!"
368//! # };
369//! // `my_struct.field` will be recorded using its `fmt::Display` implementation.
370//! event!(Level::TRACE, greeting = %my_struct.field);
371//! // is equivalent to:
372//! event!(Level::TRACE, greeting = tracing::field::display(&my_struct.field));
373//! # }
374//! ```
375//!
376//! The `%` and `?` sigils may also be used with local variable shorthand:
377//!
378//! ```
379//! # use tracing::{event, Level};
380//! # fn main() {
381//! # #[derive(Debug)]
382//! # struct MyStruct {
383//! # field: &'static str,
384//! # }
385//! #
386//! # let my_struct = MyStruct {
387//! # field: "Hello world!"
388//! # };
389//! // `my_struct.field` will be recorded using its `fmt::Display` implementation.
390//! event!(Level::TRACE, %my_struct.field);
391//! # }
392//! ```
393//!
394//! Additionally, a span may declare fields with the special value [`Empty`],
395//! which indicates that that the value for that field does not currently exist
396//! but may be recorded later. For example:
397//!
398//! ```
399//! use tracing::{trace_span, field};
400//!
401//! // Create a span with two fields: `greeting`, with the value "hello world", and
402//! // `parting`, without a value.
403//! let span = trace_span!("my_span", greeting = "hello world", parting = field::Empty);
404//!
405//! // ...
406//!
407//! // Now, record a value for parting as well.
408//! span.record("parting", &"goodbye world!");
409//! ```
410//!
411//! Finally, events may also include human-readable messages, in the form of a
412//! [format string][fmt] and (optional) arguments, **after** the event's
413//! key-value fields. If a format string and arguments are provided,
414//! they will implicitly create a new field named `message` whose value is the
415//! provided set of format arguments.
416//!
417//! For example:
418//!
419//! ```
420//! # use tracing::{event, Level};
421//! # fn main() {
422//! let question = "the ultimate question of life, the universe, and everything";
423//! let answer = 42;
424//! // records an event with the following fields:
425//! // - `question.answer` with the value 42,
426//! // - `question.tricky` with the value `true`,
427//! // - "message", with the value "the answer to the ultimate question of life, the
428//! // universe, and everything is 42."
429//! event!(
430//! Level::DEBUG,
431//! question.answer = answer,
432//! question.tricky = true,
433//! "the answer to {} is {}.", question, answer
434//! );
435//! # }
436//! ```
437//!
438//! Specifying a formatted message in this manner does not allocate by default.
439//!
440//! [struct initializers]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-the-field-init-shorthand-when-variables-and-fields-have-the-same-name
441//! [target]: Metadata::target()
442//! [parent span]: span::Attributes::parent()
443//! [determined contextually]: span::Attributes::is_contextual()
444//! [`fmt::Debug`]: std::fmt::Debug
445//! [`fmt::Display`]: std::fmt::Display
446//! [fmt]: std::fmt#usage
447//! [`Empty`]: field::Empty
448//!
449//! ### Shorthand Macros
450//!
451//! `tracing` also offers a number of macros with preset verbosity levels.
452//! The [`trace!`], [`debug!`], [`info!`], [`warn!`], and [`error!`] behave
453//! similarly to the [`event!`] macro, but with the [`Level`] argument already
454//! specified, while the corresponding [`trace_span!`], [`debug_span!`],
455//! [`info_span!`], [`warn_span!`], and [`error_span!`] macros are the same,
456//! but for the [`span!`] macro.
457//!
458//! These are intended both as a shorthand, and for compatibility with the [`log`]
459//! crate (see the next section).
460//!
461//! [`span!`]: span!
462//! [`event!`]: event!
463//! [`trace!`]: trace!
464//! [`debug!`]: debug!
465//! [`info!`]: info!
466//! [`warn!`]: warn!
467//! [`error!`]: error!
468//! [`trace_span!`]: trace_span!
469//! [`debug_span!`]: debug_span!
470//! [`info_span!`]: info_span!
471//! [`warn_span!`]: warn_span!
472//! [`error_span!`]: error_span!
473//!
474//! ### For `log` Users
475//!
476//! Users of the [`log`] crate should note that `tracing` exposes a set of
477//! macros for creating `Event`s (`trace!`, `debug!`, `info!`, `warn!`, and
478//! `error!`) which may be invoked with the same syntax as the similarly-named
479//! macros from the `log` crate. Often, the process of converting a project to
480//! use `tracing` can begin with a simple drop-in replacement.
481//!
482//! Let's consider the `log` crate's yak-shaving example:
483//!
484//! ```rust,ignore
485//! use std::{error::Error, io};
486//! use tracing::{debug, error, info, span, warn, Level};
487//!
488//! // the `#[tracing::instrument]` attribute creates and enters a span
489//! // every time the instrumented function is called. The span is named after
490//! // the function or method. Parameters passed to the function are recorded as fields.
491//! #[tracing::instrument]
492//! pub fn shave(yak: usize) -> Result<(), Box<dyn Error + 'static>> {
493//! // this creates an event at the DEBUG level with two fields:
494//! // - `excitement`, with the key "excitement" and the value "yay!"
495//! // - `message`, with the key "message" and the value "hello! I'm gonna shave a yak."
496//! //
497//! // unlike other fields, `message`'s shorthand initialization is just the string itself.
498//! debug!(excitement = "yay!", "hello! I'm gonna shave a yak.");
499//! if yak == 3 {
500//! warn!("could not locate yak!");
501//! // note that this is intended to demonstrate `tracing`'s features, not idiomatic
502//! // error handling! in a library or application, you should consider returning
503//! // a dedicated `YakError`. libraries like snafu or thiserror make this easy.
504//! return Err(io::Error::new(io::ErrorKind::Other, "shaving yak failed!").into());
505//! } else {
506//! debug!("yak shaved successfully");
507//! }
508//! Ok(())
509//! }
510//!
511//! pub fn shave_all(yaks: usize) -> usize {
512//! // Constructs a new span named "shaving_yaks" at the TRACE level,
513//! // and a field whose key is "yaks". This is equivalent to writing:
514//! //
515//! // let span = span!(Level::TRACE, "shaving_yaks", yaks = yaks);
516//! //
517//! // local variables (`yaks`) can be used as field values
518//! // without an assignment, similar to struct initializers.
519//! let span = span!(Level::TRACE, "shaving_yaks", yaks);
520//! let _enter = span.enter();
521//!
522//! info!("shaving yaks");
523//!
524//! let mut yaks_shaved = 0;
525//! for yak in 1..=yaks {
526//! let res = shave(yak);
527//! debug!(yak, shaved = res.is_ok());
528//!
529//! if let Err(ref error) = res {
530//! // Like spans, events can also use the field initialization shorthand.
531//! // In this instance, `yak` is the field being initialized.
532//! error!(yak, error = error.as_ref(), "failed to shave yak!");
533//! } else {
534//! yaks_shaved += 1;
535//! }
536//! debug!(yaks_shaved);
537//! }
538//!
539//! yaks_shaved
540//! }
541//! ```
542//!
543//! ## In libraries
544//!
545//! Libraries should link only to the `tracing` crate, and use the provided
546//! macros to record whatever information will be useful to downstream
547//! consumers.
548//!
549//! ## In executables
550//!
551//! In order to record trace events, executables have to use a collector
552//! implementation compatible with `tracing`. A collector implements a
553//! way of collecting trace data, such as by logging it to standard output.
554//!
555//! This library does not contain any `Collect` implementations; these are
556//! provided by [other crates](#related-crates).
557//!
558//! The simplest way to use a collector is to call the [`set_global_default`]
559//! function:
560//!
561//! ```
562//! # pub struct FooCollector;
563//! # use tracing::{span::{Id, Attributes, Record}, Metadata};
564//! # use tracing_core::span::Current;
565//! # impl tracing::Collect for FooCollector {
566//! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
567//! # fn record(&self, _: &Id, _: &Record) {}
568//! # fn event(&self, _: &tracing::Event) {}
569//! # fn record_follows_from(&self, _: &Id, _: &Id) {}
570//! # fn enabled(&self, _: &Metadata) -> bool { false }
571//! # fn enter(&self, _: &Id) {}
572//! # fn exit(&self, _: &Id) {}
573//! # fn current_span(&self) -> Current { Current::unknown() }
574//! # }
575//! # impl FooCollector {
576//! # fn new() -> Self { FooCollector }
577//! # }
578//! # fn main() {
579//!
580//! # #[cfg(feature = "alloc")]
581//! let my_collector = FooCollector::new();
582//! # #[cfg(feature = "alloc")]
583//! tracing::collect::set_global_default(my_collector)
584//! .expect("setting tracing default failed");
585//! # }
586//! ```
587//!
588//! <div class="information">
589//! </div><div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
590//! <strong>Warning</strong>: In general, libraries should <em>not</em> call
591//! <code>set_global_default()</code>! Doing so will cause conflicts when
592//! executables that depend on the library try to set the default later.
593//! </pre></div>
594//!
595//! This collector will be used as the default in all threads for the
596//! remainder of the duration of the program, similar to setting the logger
597//! in the `log` crate.
598//!
599//! In addition, the default collector can be set through using the
600//! [`with_default`] function. This follows the `tokio` pattern of using
601//! closures to represent executing code in a context that is exited at the end
602//! of the closure. For example:
603//!
604//! ```rust
605//! # pub struct FooCollector;
606//! # use tracing::{span::{Id, Attributes, Record}, Metadata};
607//! # use tracing_core::span::Current;
608//! # impl tracing::Collect for FooCollector {
609//! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
610//! # fn record(&self, _: &Id, _: &Record) {}
611//! # fn event(&self, _: &tracing::Event) {}
612//! # fn record_follows_from(&self, _: &Id, _: &Id) {}
613//! # fn enabled(&self, _: &Metadata) -> bool { false }
614//! # fn enter(&self, _: &Id) {}
615//! # fn exit(&self, _: &Id) {}
616//! # fn current_span(&self) -> Current { Current::unknown() }
617//! # }
618//! # impl FooCollector {
619//! # fn new() -> Self { FooCollector }
620//! # }
621//! # fn main() {
622//!
623//! let my_collector = FooCollector::new();
624//! # #[cfg(feature = "std")]
625//! tracing::collect::with_default(my_collector, || {
626//! // Any trace events generated in this closure or by functions it calls
627//! // will be collected by `my_collector`.
628//! })
629//! # }
630//! ```
631//!
632//! This approach allows trace data to be collected by multiple collectors
633//! within different contexts in the program. Note that the override only applies to the
634//! currently executing thread; other threads will not see the change from with_default.
635//!
636//! Any trace events generated outside the context of a collector will not be collected.
637//!
638//! Once a collector has been set, instrumentation points may be added to the
639//! executable using the `tracing` crate's macros.
640//!
641//! ## `log` Compatibility
642//!
643//! The [`log`] crate provides a simple, lightweight logging facade for Rust.
644//! While `tracing` builds upon `log`'s foundation with richer structured
645//! diagnostic data, `log`'s simplicity and ubiquity make it the "lowest common
646//! denominator" for text-based logging in Rust — a vast majority of Rust
647//! libraries and applications either emit or consume `log` records. Therefore,
648//! `tracing` provides multiple forms of interoperability with `log`: `tracing`
649//! instrumentation can emit `log` records, and a compatibility layer enables
650//! `tracing` [`Collect`]s to consume `log` records as `tracing` [`Event`]s.
651//!
652//! ### Emitting `log` Records
653//!
654//! This crate provides two feature flags, "log" and "log-always", which will
655//! cause [spans] and [events] to emit `log` records. When the "log" feature is
656//! enabled, if no `tracing` collector is active, invoking an event macro or
657//! creating a span with fields will emit a `log` record. This is intended
658//! primarily for use in libraries which wish to emit diagnostics that can be
659//! consumed by applications using `tracing` *or* `log`, without paying the
660//! additional overhead of emitting both forms of diagnostics when `tracing` is
661//! in use.
662//!
663//! Enabling the "log-always" feature will cause `log` records to be emitted
664//! even if a `tracing` collector _is_ set. This is intended to be used in
665//! applications where a `log` `Logger` is being used to record a textual log,
666//! and `tracing` is used only to record other forms of diagnostics (such as
667//! metrics, profiling, or distributed tracing data). Unlike the "log" feature,
668//! libraries generally should **not** enable the "log-always" feature, as doing
669//! so will prevent applications from being able to opt out of the `log` records.
670//!
671//! See [here][flags] for more details on this crate's feature flags.
672//!
673//! The generated `log` records' messages will be a string representation of the
674//! span or event's fields, and all additional information recorded by `log`
675//! (target, verbosity level, module path, file, and line number) will also be
676//! populated. Additionally, `log` records are also generated when spans are
677//! entered, exited, and closed. Since these additional span lifecycle logs have
678//! the potential to be very verbose, and don't include additional fields, they
679//! will always be emitted at the `Trace` level, rather than inheriting the
680//! level of the span that generated them. Furthermore, they are categorized
681//! under a separate `log` target, "tracing::span" (and its sub-target,
682//! "tracing::span::active", for the logs on entering and exiting a span), which
683//! may be enabled or disabled separately from other `log` records emitted by
684//! `tracing`.
685//!
686//! ### Consuming `log` Records
687//!
688//! The [`tracing-log`] crate provides a compatibility layer which
689//! allows a `tracing` collector to consume `log` records as though they
690//! were `tracing` [events]. This allows applications using `tracing` to record
691//! the logs emitted by dependencies using `log` as events within the context of
692//! the application's trace tree. See [that crate's documentation][log-tracer]
693//! for details.