1 //! A scoped, structured logging and diagnostics system.
5 //! `tracing` is a framework for instrumenting Rust programs to collect
6 //! structured, event-based diagnostic information.
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.
19 //! The `tracing` crate provides the APIs necessary for instrumenting libraries
20 //! and applications to emit trace data.
22 //! *Compiler support: [requires `rustc` 1.42+][msrv]*
24 //! [msrv]: #supported-rust-versions
27 //! The core of `tracing`'s API is composed of _spans_, _events_ and
28 //! _subscribers_. We'll cover these in turn.
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.
42 //! use tracing::{span, Level};
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`...
52 //! The [`span` module][span]'s documentation provides further details on how to
55 //! <div class="information">
56 //! <div class="tooltip compile_fail" style="">⚠ ️<span class="tooltiptext">Warning</span></div>
57 //! </div><div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
58 //! <strong>Warning</strong>: In asynchronous code that uses async/await syntax,
59 //! <code>Span::enter</code> may produce incorrect traces if the returned drop
60 //! guard is held across an await point. See
61 //! <a href="span/struct.Span.html#in-asynchronous-code">the method documentation</a>
67 //! An [`Event`] represents a _moment_ in time. It signifies something that
68 //! happened while a trace was being recorded. `Event`s are comparable to the log
69 //! records emitted by unstructured logging code, but unlike a typical log line,
70 //! an `Event` may occur within the context of a span.
74 //! use tracing::{event, span, Level};
77 //! // records an event outside of any span context:
78 //! event!(Level::INFO, "something happened");
80 //! let span = span!(Level::INFO, "my_span");
81 //! let _guard = span.enter();
83 //! // records an event within "my_span".
84 //! event!(Level::DEBUG, "something happened inside my_span");
88 //! In general, events should be used to represent points in time _within_ a
89 //! span — a request returned with a given status code, _n_ new items were
90 //! taken from a queue, and so on.
92 //! The [`Event` struct][`Event`] documentation provides further details on using
97 //! As `Span`s and `Event`s occur, they are recorded or aggregated by
98 //! implementations of the [`Subscriber`] trait. `Subscriber`s are notified
99 //! when an `Event` takes place and when a `Span` is entered or exited. These
100 //! notifications are represented by the following `Subscriber` trait methods:
102 //! + [`event`][Subscriber::event], called when an `Event` takes place,
103 //! + [`enter`], called when execution enters a `Span`,
104 //! + [`exit`], called when execution exits a `Span`
106 //! In addition, subscribers may implement the [`enabled`] function to _filter_
107 //! the notifications they receive based on [metadata] describing each `Span`
108 //! or `Event`. If a call to `Subscriber::enabled` returns `false` for a given
109 //! set of metadata, that `Subscriber` will *not* be notified about the
110 //! corresponding `Span` or `Event`. For performance reasons, if no currently
111 //! active subscribers express interest in a given set of metadata by returning
112 //! `true`, then the corresponding `Span` or `Event` will never be constructed.
116 //! First, add this to your `Cargo.toml`:
123 //! *Compiler support: requires rustc 1.39+*
125 //! ## Recording Spans and Events
127 //! Spans and events are recorded using macros.
131 //! The [`span!`] macro expands to a [`Span` struct][`Span`] which is used to
132 //! record a span. The [`Span::enter`] method on that struct records that the
133 //! span has been entered, and returns a [RAII] guard object, which will exit
134 //! the span when dropped.
139 //! use tracing::{span, Level};
141 //! // Construct a new span named "my span" with trace log level.
142 //! let span = span!(Level::TRACE, "my span");
144 //! // Enter the span, returning a guard object.
145 //! let _enter = span.enter();
147 //! // Any trace events that occur before the guard is dropped will occur
148 //! // within the span.
150 //! // Dropping the guard will exit the span.
154 //! The [`#[instrument]`][instrument] attribute provides an easy way to
155 //! add `tracing` spans to functions. A function annotated with `#[instrument]`
156 //! will create and enter a span with that function's name every time the
157 //! function is called, with arguments to that function will be recorded as
158 //! fields using `fmt::Debug`.
162 //! # // this doctest is ignored because we don't have a way to say
163 //! # // that it should only be run with cfg(feature = "attributes")
164 //! use tracing::{Level, event, instrument};
167 //! pub fn my_function(my_arg: usize) {
168 //! // This event will be recorded inside a span named `my_function` with the
169 //! // field `my_arg`.
170 //! event!(Level::INFO, "inside my_function!");
177 //! You can find more examples showing how to use this crate [here][examples].
179 //! [RAII]: https://github.com/rust-unofficial/patterns/blob/master/patterns/RAII.md
180 //! [examples]: https://github.com/tokio-rs/tracing/tree/master/examples
184 //! [`Event`]s are recorded using the [`event!`] macro:
188 //! use tracing::{event, Level};
189 //! event!(Level::INFO, "something has happened!");
193 //! ## Using the Macros
195 //! The [`span!`] and [`event!`] macros use fairly similar syntax, with some
198 //! ### Configuring Attributes
200 //! Both macros require a [`Level`] specifying the verbosity of the span or
201 //! event. Optionally, the [target] and [parent span] may be overridden. If the
202 //! target and parent span are not overridden, they will default to the
203 //! module path where the macro was invoked and the current span (as determined
204 //! by the subscriber), respectively.
209 //! # use tracing::{span, event, Level};
211 //! span!(target: "app_spans", Level::TRACE, "my span");
212 //! event!(target: "app_events", Level::INFO, "something has happened!");
216 //! # use tracing::{span, event, Level};
218 //! let span = span!(Level::TRACE, "my span");
219 //! event!(parent: &span, Level::INFO, "something has happened!");
223 //! The span macros also take a string literal after the level, to set the name
226 //! ### Recording Fields
228 //! Structured fields on spans and events are specified using the syntax
229 //! `field_name = field_value`. Fields are separated by commas.
232 //! # use tracing::{event, Level};
234 //! // records an event with two fields:
235 //! // - "answer", with the value 42
236 //! // - "question", with the value "life, the universe and everything"
237 //! event!(Level::INFO, answer = 42, question = "life, the universe, and everything");
241 //! As shorthand, local variables may be used as field values without an
242 //! assignment, similar to [struct initializers]. For example:
245 //! # use tracing::{span, Level};
247 //! let user = "ferris";
249 //! span!(Level::TRACE, "login", user);
250 //! // is equivalent to:
251 //! span!(Level::TRACE, "login", user = user);
255 //! Field names can include dots, but should not be terminated by them:
257 //! # use tracing::{span, Level};
259 //! let user = "ferris";
260 //! let email = "ferris@rust-lang.org";
261 //! span!(Level::TRACE, "login", user, user.email = email);
265 //! Since field names can include dots, fields on local structs can be used
266 //! using the local variable shorthand:
268 //! # use tracing::{span, Level};
271 //! # name: &'static str,
272 //! # email: &'static str,
274 //! let user = User {
276 //! email: "ferris@rust-lang.org",
278 //! // the span will have the fields `user.name = "ferris"` and
279 //! // `user.email = "ferris@rust-lang.org"`.
280 //! span!(Level::TRACE, "login", user.name, user.email);
284 //! Fields with names that are not Rust identifiers, or with names that are Rust reserved words,
285 //! may be created using quoted string literals. However, this may not be used with the local
286 //! variable shorthand.
288 //! # use tracing::{span, Level};
290 //! // records an event with fields whose names are not Rust identifiers
291 //! // - "guid:x-request-id", containing a `:`, with the value "abcdef"
292 //! // - "type", which is a reserved word, with the value "request"
293 //! span!(Level::TRACE, "api", "guid:x-request-id" = "abcdef", "type" = "request");
297 //! The `?` sigil is shorthand that specifies a field should be recorded using
298 //! its [`fmt::Debug`] implementation:
300 //! # use tracing::{event, Level};
303 //! struct MyStruct {
304 //! field: &'static str,
307 //! let my_struct = MyStruct {
308 //! field: "Hello world!"
311 //! // `my_struct` will be recorded using its `fmt::Debug` implementation.
312 //! event!(Level::TRACE, greeting = ?my_struct);
313 //! // is equivalent to:
314 //! event!(Level::TRACE, greeting = tracing::field::debug(&my_struct));
318 //! The `%` sigil operates similarly, but indicates that the value should be
319 //! recorded using its [`fmt::Display`] implementation:
321 //! # use tracing::{event, Level};
323 //! # #[derive(Debug)]
324 //! # struct MyStruct {
325 //! # field: &'static str,
328 //! # let my_struct = MyStruct {
329 //! # field: "Hello world!"
331 //! // `my_struct.field` will be recorded using its `fmt::Display` implementation.
332 //! event!(Level::TRACE, greeting = %my_struct.field);
333 //! // is equivalent to:
334 //! event!(Level::TRACE, greeting = tracing::field::display(&my_struct.field));
338 //! The `%` and `?` sigils may also be used with local variable shorthand:
341 //! # use tracing::{event, Level};
343 //! # #[derive(Debug)]
344 //! # struct MyStruct {
345 //! # field: &'static str,
348 //! # let my_struct = MyStruct {
349 //! # field: "Hello world!"
351 //! // `my_struct.field` will be recorded using its `fmt::Display` implementation.
352 //! event!(Level::TRACE, %my_struct.field);
356 //! Additionally, a span may declare fields with the special value [`Empty`],
357 //! which indicates that that the value for that field does not currently exist
358 //! but may be recorded later. For example:
361 //! use tracing::{trace_span, field};
363 //! // Create a span with two fields: `greeting`, with the value "hello world", and
364 //! // `parting`, without a value.
365 //! let span = trace_span!("my_span", greeting = "hello world", parting = field::Empty);
369 //! // Now, record a value for parting as well.
370 //! span.record("parting", &"goodbye world!");
373 //! Note that a span may have up to 32 fields. The following will not compile:
375 //! ```rust,compile_fail
376 //! # use tracing::Level;
378 //! let bad_span = span!(
380 //! "too many fields!",
381 //! a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8, i = 9,
382 //! j = 10, k = 11, l = 12, m = 13, n = 14, o = 15, p = 16, q = 17,
383 //! r = 18, s = 19, t = 20, u = 21, v = 22, w = 23, x = 24, y = 25,
384 //! z = 26, aa = 27, bb = 28, cc = 29, dd = 30, ee = 31, ff = 32, gg = 33
389 //! Finally, events may also include human-readable messages, in the form of a
390 //! [format string][fmt] and (optional) arguments, **after** the event's
391 //! key-value fields. If a format string and arguments are provided,
392 //! they will implicitly create a new field named `message` whose value is the
393 //! provided set of format arguments.
398 //! # use tracing::{event, Level};
400 //! let question = "the answer to the ultimate question of life, the universe, and everything";
402 //! // records an event with the following fields:
403 //! // - `question.answer` with the value 42,
404 //! // - `question.tricky` with the value `true`,
405 //! // - "message", with the value "the answer to the ultimate question of life, the
406 //! // universe, and everything is 42."
409 //! question.answer = answer,
410 //! question.tricky = true,
411 //! "the answer to {} is {}.", question, answer
416 //! Specifying a formatted message in this manner does not allocate by default.
418 //! [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
419 //! [target]: struct.Metadata.html#method.target
420 //! [parent span]: span/struct.Attributes.html#method.parent
421 //! [determined contextually]: span/struct.Attributes.html#method.is_contextual
422 //! [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
423 //! [`fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
424 //! [fmt]: https://doc.rust-lang.org/std/fmt/#usage
425 //! [`Empty`]: field/struct.Empty.html
427 //! ### Shorthand Macros
429 //! `tracing` also offers a number of macros with preset verbosity levels.
430 //! The [`trace!`], [`debug!`], [`info!`], [`warn!`], and [`error!`] behave
431 //! similarly to the [`event!`] macro, but with the [`Level`] argument already
432 //! specified, while the corresponding [`trace_span!`], [`debug_span!`],
433 //! [`info_span!`], [`warn_span!`], and [`error_span!`] macros are the same,
434 //! but for the [`span!`] macro.
436 //! These are intended both as a shorthand, and for compatibility with the [`log`]
437 //! crate (see the next section).
439 //! [`span!`]: macro.span.html
440 //! [`event!`]: macro.event.html
441 //! [`trace!`]: macro.trace.html
442 //! [`debug!`]: macro.debug.html
443 //! [`info!`]: macro.info.html
444 //! [`warn!`]: macro.warn.html
445 //! [`error!`]: macro.error.html
446 //! [`trace_span!`]: macro.trace_span.html
447 //! [`debug_span!`]: macro.debug_span.html
448 //! [`info_span!`]: macro.info_span.html
449 //! [`warn_span!`]: macro.warn_span.html
450 //! [`error_span!`]: macro.error_span.html
451 //! [`Level`]: struct.Level.html
453 //! ### For `log` Users
455 //! Users of the [`log`] crate should note that `tracing` exposes a set of
456 //! macros for creating `Event`s (`trace!`, `debug!`, `info!`, `warn!`, and
457 //! `error!`) which may be invoked with the same syntax as the similarly-named
458 //! macros from the `log` crate. Often, the process of converting a project to
459 //! use `tracing` can begin with a simple drop-in replacement.
461 //! Let's consider the `log` crate's yak-shaving example:
464 //! use std::{error::Error, io};
465 //! use tracing::{debug, error, info, span, warn, Level};
467 //! // the `#[tracing::instrument]` attribute creates and enters a span
468 //! // every time the instrumented function is called. The span is named after the
469 //! // the function or method. Parameters passed to the function are recorded as fields.
470 //! #[tracing::instrument]
471 //! pub fn shave(yak: usize) -> Result<(), Box<dyn Error + 'static>> {
472 //! // this creates an event at the DEBUG level with two fields:
473 //! // - `excitement`, with the key "excitement" and the value "yay!"
474 //! // - `message`, with the key "message" and the value "hello! I'm gonna shave a yak."
476 //! // unlike other fields, `message`'s shorthand initialization is just the string itself.
477 //! debug!(excitement = "yay!", "hello! I'm gonna shave a yak.");
479 //! warn!("could not locate yak!");
480 //! // note that this is intended to demonstrate `tracing`'s features, not idiomatic
481 //! // error handling! in a library or application, you should consider returning
482 //! // a dedicated `YakError`. libraries like snafu or thiserror make this easy.
483 //! return Err(io::Error::new(io::ErrorKind::Other, "shaving yak failed!").into());
485 //! debug!("yak shaved successfully");
490 //! pub fn shave_all(yaks: usize) -> usize {
491 //! // Constructs a new span named "shaving_yaks" at the TRACE level,
492 //! // and a field whose key is "yaks". This is equivalent to writing:
494 //! // let span = span!(Level::TRACE, "shaving_yaks", yaks = yaks);
496 //! // local variables (`yaks`) can be used as field values
497 //! // without an assignment, similar to struct initializers.
498 //! let span = span!(Level::TRACE, "shaving_yaks", yaks);
499 //! let _enter = span.enter();
501 //! info!("shaving yaks");
503 //! let mut yaks_shaved = 0;
504 //! for yak in 1..=yaks {
505 //! let res = shave(yak);
506 //! debug!(yak, shaved = res.is_ok());
508 //! if let Err(ref error) = res {
509 //! // Like spans, events can also use the field initialization shorthand.
510 //! // In this instance, `yak` is the field being initalized.
511 //! error!(yak, error = error.as_ref(), "failed to shave yak!");
513 //! yaks_shaved += 1;
515 //! debug!(yaks_shaved);
524 //! Libraries should link only to the `tracing` crate, and use the provided
525 //! macros to record whatever information will be useful to downstream
528 //! ## In executables
530 //! In order to record trace events, executables have to use a `Subscriber`
531 //! implementation compatible with `tracing`. A `Subscriber` implements a
532 //! way of collecting trace data, such as by logging it to standard output.
534 //! This library does not contain any `Subscriber` implementations; these are
535 //! provided by [other crates](#related-crates).
537 //! The simplest way to use a subscriber is to call the [`set_global_default`]
541 //! extern crate tracing;
542 //! # pub struct FooSubscriber;
543 //! # use tracing::{span::{Id, Attributes, Record}, Metadata};
544 //! # impl tracing::Subscriber for FooSubscriber {
545 //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
546 //! # fn record(&self, _: &Id, _: &Record) {}
547 //! # fn event(&self, _: &tracing::Event) {}
548 //! # fn record_follows_from(&self, _: &Id, _: &Id) {}
549 //! # fn enabled(&self, _: &Metadata) -> bool { false }
550 //! # fn enter(&self, _: &Id) {}
551 //! # fn exit(&self, _: &Id) {}
553 //! # impl FooSubscriber {
554 //! # fn new() -> Self { FooSubscriber }
558 //! let my_subscriber = FooSubscriber::new();
559 //! tracing::subscriber::set_global_default(my_subscriber)
560 //! .expect("setting tracing default failed");
564 //! <div class="information">
565 //! <div class="tooltip compile_fail" style="">⚠ ️<span class="tooltiptext">Warning</span></div>
566 //! </div><div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
567 //! <strong>Warning</strong>: In general, libraries should <em>not</em> call
568 //! <code>set_global_default()</code>! Doing so will cause conflicts when
569 //! executables that depend on the library try to set the default later.
572 //! This subscriber will be used as the default in all threads for the
573 //! remainder of the duration of the program, similar to setting the logger
574 //! in the `log` crate.
576 //! In addition, the default subscriber can be set through using the
577 //! [`with_default`] function. This follows the `tokio` pattern of using
578 //! closures to represent executing code in a context that is exited at the end
579 //! of the closure. For example:
582 //! # pub struct FooSubscriber;
583 //! # use tracing::{span::{Id, Attributes, Record}, Metadata};
584 //! # impl tracing::Subscriber for FooSubscriber {
585 //! # fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
586 //! # fn record(&self, _: &Id, _: &Record) {}
587 //! # fn event(&self, _: &tracing::Event) {}
588 //! # fn record_follows_from(&self, _: &Id, _: &Id) {}
589 //! # fn enabled(&self, _: &Metadata) -> bool { false }
590 //! # fn enter(&self, _: &Id) {}
591 //! # fn exit(&self, _: &Id) {}
593 //! # impl FooSubscriber {
594 //! # fn new() -> Self { FooSubscriber }
598 //! let my_subscriber = FooSubscriber::new();
599 //! # #[cfg(feature = "std")]
600 //! tracing::subscriber::with_default(my_subscriber, || {
601 //! // Any trace events generated in this closure or by functions it calls
602 //! // will be collected by `my_subscriber`.
607 //! This approach allows trace data to be collected by multiple subscribers
608 //! within different contexts in the program. Note that the override only applies to the
609 //! currently executing thread; other threads will not see the change from with_default.
611 //! Any trace events generated outside the context of a subscriber will not be collected.
613 //! Once a subscriber has been set, instrumentation points may be added to the
614 //! executable using the `tracing` crate's macros.
616 //! ## `log` Compatibility
618 //! The [`log`] crate provides a simple, lightweight logging facade for Rust.
619 //! While `tracing` builds upon `log`'s foundation with richer structured
620 //! diagnostic data, `log`'s simplicity and ubiquity make it the "lowest common
621 //! denominator" for text-based logging in Rust — a vast majority of Rust
622 //! libraries and applications either emit or consume `log` records. Therefore,
623 //! `tracing` provides multiple forms of interoperability with `log`: `tracing`
624 //! instrumentation can emit `log` records, and a compatibility layer enables
625 //! `tracing` [`Subscriber`]s to consume `log` records as `tracing` [`Event`]s.
627 //! ### Emitting `log` Records
629 //! This crate provides two feature flags, "log" and "log-always", which will
630 //! cause [spans] and [events] to emit `log` records. When the "log" feature is
631 //! enabled, if no `tracing` `Subscriber` is active, invoking an event macro or
632 //! creating a span with fields will emit a `log` record. This is intended
633 //! primarily for use in libraries which wish to emit diagnostics that can be
634 //! consumed by applications using `tracing` *or* `log`, without paying the
635 //! additional overhead of emitting both forms of diagnostics when `tracing` is
638 //! Enabling the "log-always" feature will cause `log` records to be emitted
639 //! even if a `tracing` `Subscriber` _is_ set. This is intended to be used in
640 //! applications where a `log` `Logger` is being used to record a textual log,
641 //! and `tracing` is used only to record other forms of diagnostics (such as
642 //! metrics, profiling, or distributed tracing data). Unlike the "log" feature,
643 //! libraries generally should **not** enable the "log-always" feature, as doing
644 //! so will prevent applications from being able to opt out of the `log` records.
646 //! See [here][flags] for more details on this crate's feature flags.
648 //! The generated `log` records' messages will be a string representation of the
649 //! span or event's fields, and all additional information recorded by `log`
650 //! (target, verbosity level, module path, file, and line number) will also be
651 //! populated. Additionally, `log` records are also generated when spans are
652 //! entered, exited, and closed. Since these additional span lifecycle logs have
653 //! the potential to be very verbose, and don't include additional fields, they
654 //! will always be emitted at the `Trace` level, rather than inheriting the
655 //! level of the span that generated them. Furthermore, they are are categorized
656 //! under a separate `log` target, "tracing::span" (and its sub-target,
657 //! "tracing::span::active", for the logs on entering and exiting a span), which
658 //! may be enabled or disabled separately from other `log` records emitted by
661 //! ### Consuming `log` Records
663 //! The [`tracing-log`] crate provides a compatibility layer which
664 //! allows a `tracing` [`Subscriber`] to consume `log` records as though they
665 //! were `tracing` [events]. This allows applications using `tracing` to record
666 //! the logs emitted by dependencies using `log` as events within the context of
667 //! the application's trace tree. See [that crate's documentation][log-tracer]
670 //! [log-tracer]: https://docs.rs/tracing-log/latest/tracing_log/#convert-log-records-to-tracing-events
672 //! ## Related Crates
674 //! In addition to `tracing` and `tracing-core`, the [`tokio-rs/tracing`] repository
675 //! contains several additional crates designed to be used with the `tracing` ecosystem.
676 //! This includes a collection of `Subscriber` implementations, as well as utility
677 //! and adapter crates to assist in writing `Subscriber`s and instrumenting
680 //! In particular, the following crates are likely to be of interest:
682 //! - [`tracing-futures`] provides a compatibility layer with the `futures`
683 //! crate, allowing spans to be attached to `Future`s, `Stream`s, and `Executor`s.
684 //! - [`tracing-subscriber`] provides `Subscriber` implementations and
685 //! utilities for working with `Subscriber`s. This includes a [`FmtSubscriber`]
686 //! `FmtSubscriber` for logging formatted trace data to stdout, with similar
687 //! filtering and formatting to the [`env_logger`] crate.
688 //! - [`tracing-log`] provides a compatibility layer with the [`log`] crate,
689 //! allowing log messages to be recorded as `tracing` `Event`s within the
690 //! trace tree. This is useful when a project using `tracing` have
691 //! dependencies which use `log`. Note that if you're using
692 //! `tracing-subscriber`'s `FmtSubscriber`, you don't need to depend on
693 //! `tracing-log` directly.
694 //! - [`tracing-appender`] provides utilities for outputting tracing data,
695 //! including a file appender and non blocking writer.
697 //! Additionally, there are also several third-party crates which are not
698 //! maintained by the `tokio` project. These include:
700 //! - [`tracing-timing`] implements inter-event timing metrics on top of `tracing`.
701 //! It provides a subscriber that records the time elapsed between pairs of
702 //! `tracing` events and generates histograms.
703 //! - [`tracing-opentelemetry`] provides a subscriber for emitting traces to
704 //! [OpenTelemetry]-compatible distributed tracing systems.
705 //! - [`tracing-honeycomb`] Provides a layer that reports traces spanning multiple machines to [honeycomb.io]. Backed by [`tracing-distributed`].
706 //! - [`tracing-distributed`] Provides a generic implementation of a layer that reports traces spanning multiple machines to some backend.
707 //! - [`tracing-actix`] provides `tracing` integration for the `actix` actor
709 //! - [`tracing-gelf`] implements a subscriber for exporting traces in Greylog
711 //! - [`tracing-coz`] provides integration with the [coz] causal profiler
713 //! - [`tracing-bunyan-formatter`] provides a layer implementation that reports events and spans
714 //! in [bunyan] format, enriched with timing information.
715 //! - [`tracing-wasm`] provides a `Subscriber`/`Layer` implementation that reports
716 //! events and spans via browser `console.log` and [User Timing API (`window.performance`)].
717 //! - [`tide-tracing`] provides a [tide] middleware to trace all incoming requests and responses.
718 //! - [`test-env-log`] takes care of initializing `tracing` for tests, based on
719 //! environment variables with an `env_logger` compatible syntax.
720 //! - [`tracing-unwrap`] provides convenience methods to report failed unwraps
721 //! on `Result` or `Option` types to a `Subscriber`.
722 //! - [`diesel-tracing`] provides integration with [`diesel`] database connections.
723 //! - [`tracing-tracy`] provides a way to collect [Tracy] profiles in instrumented
726 //! If you're the maintainer of a `tracing` ecosystem crate not listed above,
727 //! please let us know! We'd love to add your project to the list!
729 //! [`tracing-opentelemetry`]: https://crates.io/crates/tracing-opentelemetry
730 //! [OpenTelemetry]: https://opentelemetry.io/
731 //! [`tracing-honeycomb`]: https://crates.io/crates/tracing-honeycomb
732 //! [`tracing-distributed`]: https://crates.io/crates/tracing-distributed
733 //! [honeycomb.io]: https://www.honeycomb.io/
734 //! [`tracing-actix`]: https://crates.io/crates/tracing-actix
735 //! [`tracing-gelf`]: https://crates.io/crates/tracing-gelf
736 //! [`tracing-coz`]: https://crates.io/crates/tracing-coz
737 //! [coz]: https://github.com/plasma-umass/coz
738 //! [`tracing-bunyan-formatter`]: https://crates.io/crates/tracing-bunyan-formatter
739 //! [bunyan]: https://github.com/trentm/node-bunyan
740 //! [`tracing-wasm`]: https://docs.rs/tracing-wasm
741 //! [User Timing API (`window.performance`)]: https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API
742 //! [`tide-tracing`]: https://crates.io/crates/tide-tracing
743 //! [tide]: https://crates.io/crates/tide
744 //! [`test-env-log`]: https://crates.io/crates/test-env-log
745 //! [`tracing-unwrap`]: https://docs.rs/tracing-unwrap
746 //! [`diesel`]: https://crates.io/crates/diesel
747 //! [`diesel-tracing`]: https://crates.io/crates/diesel-tracing
748 //! [`tracing-tracy`]: https://crates.io/crates/tracing-tracy
749 //! [Tracy]: https://github.com/wolfpld/tracy
751 //! <div class="information">
752 //! <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div>
754 //! <div class="example-wrap" style="display:inline-block">
755 //! <pre class="ignore" style="white-space:normal;font:inherit;">
756 //! <strong>Note</strong>: Some of these ecosystem crates are currently
757 //! unreleased and/or in earlier stages of development. They may be less stable
758 //! than <code>tracing</code> and <code>tracing-core</code>.
761 //! ## Crate Feature Flags
763 //! The following crate feature flags are available:
765 //! * A set of features controlling the [static verbosity level].
766 //! * `log`: causes trace instrumentation points to emit [`log`] records as well
767 //! as trace events, if a default `tracing` subscriber has not been set. This
768 //! is intended for use in libraries whose users may be using either `tracing`
770 //! * `log-always`: Emit `log` records from all `tracing` spans and events, even
771 //! if a `tracing` subscriber has been set. This should be set only by
772 //! applications which intend to collect traces and logs separately; if an
773 //! adapter is used to convert `log` records into `tracing` events, this will
774 //! cause duplicate events to occur.
775 //! * `attributes`: Includes support for the `#[instrument]` attribute.
776 //! This is on by default, but does bring in the `syn` crate as a dependency,
777 //! which may add to the compile time of crates that do not already use it.
778 //! * `std`: Depend on the Rust standard library (enabled by default).
780 //! `no_std` users may disable this feature with `default-features = false`:
784 //! tracing = { version = "0.1.22", default-features = false }
787 //! <div class="information">
788 //! <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div>
790 //! <div class="example-wrap" style="display:inline-block">
791 //! <pre class="ignore" style="white-space:normal;font:inherit;">
792 //! <strong>Note</strong>: <code>tracing</code>'s <code>no_std</code> support
793 //! requires <code>liballoc</code>.
796 //! ## Supported Rust Versions
798 //! Tracing is built against the latest stable release. The minimum supported
799 //! version is 1.42. The current Tracing version is not guaranteed to build on
800 //! Rust versions earlier than the minimum supported version.
802 //! Tracing follows the same compiler support policies as the rest of the Tokio
803 //! project. The current stable Rust compiler and the three most recent minor
804 //! versions before it will always be supported. For example, if the current
805 //! stable compiler version is 1.45, the minimum supported version will not be
806 //! increased past 1.42, three minor versions prior. Increasing the minimum
807 //! supported compiler version is not considered a semver breaking change as
808 //! long as doing so complies with this policy.
810 //! [`log`]: https://docs.rs/log/0.4.6/log/
812 //! [spans]: mod@span
813 //! [`Span`]: span::Span
814 //! [`in_scope`]: span::Span::in_scope
817 //! [`Subscriber`]: subscriber::Subscriber
818 //! [Subscriber::event]: subscriber::Subscriber::event
819 //! [`enter`]: subscriber::Subscriber::enter
820 //! [`exit`]: subscriber::Subscriber::exit
821 //! [`enabled`]: subscriber::Subscriber::enabled
822 //! [metadata]: Metadata
823 //! [`field::display`]: field::display
824 //! [`field::debug`]: field::debug
825 //! [`set_global_default`]: subscriber::set_global_default
826 //! [`with_default`]: subscriber::with_default
827 //! [`tokio-rs/tracing`]: https://github.com/tokio-rs/tracing
828 //! [`tracing-futures`]: https://crates.io/crates/tracing-futures
829 //! [`tracing-subscriber`]: https://crates.io/crates/tracing-subscriber
830 //! [`tracing-log`]: https://crates.io/crates/tracing-log
831 //! [`tracing-timing`]: https://crates.io/crates/tracing-timing
832 //! [`tracing-appender`]: https://crates.io/crates/tracing-appender
833 //! [`env_logger`]: https://crates.io/crates/env_logger
834 //! [`FmtSubscriber`]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/struct.Subscriber.html
835 //! [static verbosity level]: level_filters/index.html#compile-time-filters
836 //! [instrument]: https://docs.rs/tracing-attributes/latest/tracing_attributes/attr.instrument.html
837 //! [flags]: #crate-feature-flags
838 #![cfg_attr(not(feature = "std"), no_std)]
839 #![cfg_attr(docsrs, feature(doc_cfg), deny(broken_intra_doc_links))]
840 #![doc(html_root_url = "https://docs.rs/tracing/0.1.22")]
842 html_logo_url
= "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png",
843 issue_tracker_base_url
= "https://github.com/tokio-rs/tracing/issues/"
846 missing_debug_implementations
,
854 non_shorthand_field_patterns
,
855 no_mangle_generic_items
,
856 overflowing_literals
,
858 patterns_in_fns_without_body
,
860 unconditional_recursion
,
868 #[cfg(not(feature = "std"))]
874 #[cfg(feature = "log")]
878 // Somehow this `use` statement is necessary for us to re-export the `core`
879 // macros on Rust 1.26.0. I'm not sure how this makes it work, but it does.
880 #[allow(unused_imports)]
885 pub use self::instrument
::Instrument
;
886 pub use self::{dispatcher::Dispatch, event::Event, field::Value, subscriber::Subscriber}
;
889 pub use self::span
::Id
;
892 pub use tracing_core
::{
893 callsite
::{self, Callsite}
,
896 pub use tracing_core
::{event, Level, Metadata}
;
899 pub use self::span
::Span
;
900 #[cfg(feature = "attributes")]
901 #[cfg_attr(docsrs, doc(cfg(feature = "attributes")))]
903 pub use tracing_attributes
::instrument
;
910 /// Attach a span to a `std::future::Future`.
912 pub mod level_filters
;
914 pub(crate) mod stdlib
;
918 pub mod __macro_support
{
919 pub use crate::callsite
::Callsite
;
920 use crate::stdlib
::sync
::atomic
::{AtomicUsize, Ordering}
;
921 use crate::{subscriber::Interest, Metadata}
;
922 use tracing_core
::Once
;
924 /// Callsite implementation used by macro-generated code.
926 /// /!\ WARNING: This is *not* a stable API! /!\
927 /// This type, and all code contained in the `__macro_support` module, is
928 /// a *private* API of `tracing`. It is exposed publicly because it is used
929 /// by the `tracing` macros, but it is not part of the stable versioned API.
930 /// Breaking changes to this module may occur in small-numbered versions
933 pub struct MacroCallsite
{
934 interest
: AtomicUsize
,
935 meta
: &'
static Metadata
<'
static>,
940 /// Returns a new `MacroCallsite` with the specified `Metadata`.
942 /// /!\ WARNING: This is *not* a stable API! /!\
943 /// This method, and all code contained in the `__macro_support` module, is
944 /// a *private* API of `tracing`. It is exposed publicly because it is used
945 /// by the `tracing` macros, but it is not part of the stable versioned API.
946 /// Breaking changes to this module may occur in small-numbered versions
948 pub const fn new(meta
: &'
static Metadata
<'
static>) -> Self {
950 interest
: AtomicUsize
::new(0xDEADFACED),
952 registration
: Once
::new(),
956 /// Registers this callsite with the global callsite registry.
958 /// If the callsite is already registered, this does nothing.
960 /// /!\ WARNING: This is *not* a stable API! /!\
961 /// This method, and all code contained in the `__macro_support` module, is
962 /// a *private* API of `tracing`. It is exposed publicly because it is used
963 /// by the `tracing` macros, but it is not part of the stable versioned API.
964 /// Breaking changes to this module may occur in small-numbered versions
967 // This only happens once (or if the cached interest value was corrupted).
969 pub fn register(&'
static self) -> Interest
{
971 .call_once(|| crate::callsite
::register(self));
972 match self.interest
.load(Ordering
::Relaxed
) {
973 0 => Interest
::never(),
974 2 => Interest
::always(),
975 _
=> Interest
::sometimes(),
979 /// Returns the callsite's cached Interest, or registers it for the
980 /// first time if it has not yet been registered.
982 /// /!\ WARNING: This is *not* a stable API! /!\
983 /// This method, and all code contained in the `__macro_support` module, is
984 /// a *private* API of `tracing`. It is exposed publicly because it is used
985 /// by the `tracing` macros, but it is not part of the stable versioned API.
986 /// Breaking changes to this module may occur in small-numbered versions
989 pub fn interest(&'
static self) -> Interest
{
990 match self.interest
.load(Ordering
::Relaxed
) {
991 0 => Interest
::never(),
992 1 => Interest
::sometimes(),
993 2 => Interest
::always(),
994 _
=> self.register(),
998 pub fn is_enabled(&self, interest
: Interest
) -> bool
{
1000 || crate::dispatcher
::get_default(|default| default.enabled(self.meta
))
1004 #[cfg(feature = "log")]
1005 pub fn disabled_span(&self) -> crate::Span
{
1006 crate::Span
::new_disabled(self.meta
)
1010 #[cfg(not(feature = "log"))]
1011 pub fn disabled_span(&self) -> crate::Span
{
1016 impl Callsite
for MacroCallsite
{
1017 fn set_interest(&self, interest
: Interest
) {
1018 let interest
= match () {
1019 _
if interest
.is_never() => 0,
1020 _
if interest
.is_always() => 2,
1023 self.interest
.store(interest
, Ordering
::SeqCst
);
1027 fn metadata(&self) -> &Metadata
<'
static> {