]> git.proxmox.com Git - rustc.git/blob - vendor/tracing/src/lib.rs
New upstream version 1.51.0+dfsg1
[rustc.git] / vendor / tracing / src / 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.42+][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 //! _subscribers_. 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][span]'s documentation provides further details on how to
53 //! use spans.
54 //!
55 //! <div class="information">
56 //! <div class="tooltip compile_fail" style="">&#x26a0; &#xfe0f;<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>
62 //! for details.
63 //! </pre></div>
64 //!
65 //! ## Events
66 //!
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.
71 //!
72 //! For example:
73 //! ```
74 //! use tracing::{event, span, Level};
75 //!
76 //! # fn main() {
77 //! // records an event outside of any span context:
78 //! event!(Level::INFO, "something happened");
79 //!
80 //! let span = span!(Level::INFO, "my_span");
81 //! let _guard = span.enter();
82 //!
83 //! // records an event within "my_span".
84 //! event!(Level::DEBUG, "something happened inside my_span");
85 //! # }
86 //!```
87 //!
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.
91 //!
92 //! The [`Event` struct][`Event`] documentation provides further details on using
93 //! events.
94 //!
95 //! ## Subscribers
96 //!
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:
101 //!
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`
105 //!
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.
113 //!
114 //! # Usage
115 //!
116 //! First, add this to your `Cargo.toml`:
117 //!
118 //! ```toml
119 //! [dependencies]
120 //! tracing = "0.1"
121 //! ```
122 //!
123 //! *Compiler support: requires rustc 1.39+*
124 //!
125 //! ## Recording Spans and Events
126 //!
127 //! Spans and events are recorded using macros.
128 //!
129 //! ### Spans
130 //!
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.
135 //!
136 //! For example:
137 //!
138 //! ```rust
139 //! use tracing::{span, Level};
140 //! # fn main() {
141 //! // Construct a new span named "my span" with trace log level.
142 //! let span = span!(Level::TRACE, "my span");
143 //!
144 //! // Enter the span, returning a guard object.
145 //! let _enter = span.enter();
146 //!
147 //! // Any trace events that occur before the guard is dropped will occur
148 //! // within the span.
149 //!
150 //! // Dropping the guard will exit the span.
151 //! # }
152 //! ```
153 //!
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`.
159 //!
160 //! For example:
161 //! ```ignore
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};
165 //!
166 //! #[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!");
171 //! // ...
172 //! }
173 //! # fn main() {}
174 //! ```
175 //!
176 //!
177 //! You can find more examples showing how to use this crate [here][examples].
178 //!
179 //! [RAII]: https://github.com/rust-unofficial/patterns/blob/master/patterns/RAII.md
180 //! [examples]: https://github.com/tokio-rs/tracing/tree/master/examples
181 //!
182 //! ### Events
183 //!
184 //! [`Event`]s are recorded using the [`event!`] macro:
185 //!
186 //! ```rust
187 //! # fn main() {
188 //! use tracing::{event, Level};
189 //! event!(Level::INFO, "something has happened!");
190 //! # }
191 //! ```
192 //!
193 //! ## Using the Macros
194 //!
195 //! The [`span!`] and [`event!`] macros use fairly similar syntax, with some
196 //! exceptions.
197 //!
198 //! ### Configuring Attributes
199 //!
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.
205 //!
206 //! For example:
207 //!
208 //! ```
209 //! # use tracing::{span, event, Level};
210 //! # fn main() {
211 //! span!(target: "app_spans", Level::TRACE, "my span");
212 //! event!(target: "app_events", Level::INFO, "something has happened!");
213 //! # }
214 //! ```
215 //! ```
216 //! # use tracing::{span, event, Level};
217 //! # fn main() {
218 //! let span = span!(Level::TRACE, "my span");
219 //! event!(parent: &span, Level::INFO, "something has happened!");
220 //! # }
221 //! ```
222 //!
223 //! The span macros also take a string literal after the level, to set the name
224 //! of the span.
225 //!
226 //! ### Recording Fields
227 //!
228 //! Structured fields on spans and events are specified using the syntax
229 //! `field_name = field_value`. Fields are separated by commas.
230 //!
231 //! ```
232 //! # use tracing::{event, Level};
233 //! # fn main() {
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");
238 //! # }
239 //! ```
240 //!
241 //! As shorthand, local variables may be used as field values without an
242 //! assignment, similar to [struct initializers]. For example:
243 //!
244 //! ```
245 //! # use tracing::{span, Level};
246 //! # fn main() {
247 //! let user = "ferris";
248 //!
249 //! span!(Level::TRACE, "login", user);
250 //! // is equivalent to:
251 //! span!(Level::TRACE, "login", user = user);
252 //! # }
253 //!```
254 //!
255 //! Field names can include dots, but should not be terminated by them:
256 //! ```
257 //! # use tracing::{span, Level};
258 //! # fn main() {
259 //! let user = "ferris";
260 //! let email = "ferris@rust-lang.org";
261 //! span!(Level::TRACE, "login", user, user.email = email);
262 //! # }
263 //!```
264 //!
265 //! Since field names can include dots, fields on local structs can be used
266 //! using the local variable shorthand:
267 //! ```
268 //! # use tracing::{span, Level};
269 //! # fn main() {
270 //! # struct User {
271 //! # name: &'static str,
272 //! # email: &'static str,
273 //! # }
274 //! let user = User {
275 //! name: "ferris",
276 //! email: "ferris@rust-lang.org",
277 //! };
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);
281 //! # }
282 //!```
283 //!
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.
287 //! ```
288 //! # use tracing::{span, Level};
289 //! # fn main() {
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");
294 //! # }
295 //!```
296 //!
297 //! The `?` sigil is shorthand that specifies a field should be recorded using
298 //! its [`fmt::Debug`] implementation:
299 //! ```
300 //! # use tracing::{event, Level};
301 //! # fn main() {
302 //! #[derive(Debug)]
303 //! struct MyStruct {
304 //! field: &'static str,
305 //! }
306 //!
307 //! let my_struct = MyStruct {
308 //! field: "Hello world!"
309 //! };
310 //!
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));
315 //! # }
316 //! ```
317 //!
318 //! The `%` sigil operates similarly, but indicates that the value should be
319 //! recorded using its [`fmt::Display`] implementation:
320 //! ```
321 //! # use tracing::{event, Level};
322 //! # fn main() {
323 //! # #[derive(Debug)]
324 //! # struct MyStruct {
325 //! # field: &'static str,
326 //! # }
327 //! #
328 //! # let my_struct = MyStruct {
329 //! # field: "Hello world!"
330 //! # };
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));
335 //! # }
336 //! ```
337 //!
338 //! The `%` and `?` sigils may also be used with local variable shorthand:
339 //!
340 //! ```
341 //! # use tracing::{event, Level};
342 //! # fn main() {
343 //! # #[derive(Debug)]
344 //! # struct MyStruct {
345 //! # field: &'static str,
346 //! # }
347 //! #
348 //! # let my_struct = MyStruct {
349 //! # field: "Hello world!"
350 //! # };
351 //! // `my_struct.field` will be recorded using its `fmt::Display` implementation.
352 //! event!(Level::TRACE, %my_struct.field);
353 //! # }
354 //! ```
355 //!
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:
359 //!
360 //! ```
361 //! use tracing::{trace_span, field};
362 //!
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);
366 //!
367 //! // ...
368 //!
369 //! // Now, record a value for parting as well.
370 //! span.record("parting", &"goodbye world!");
371 //! ```
372 //!
373 //! Note that a span may have up to 32 fields. The following will not compile:
374 //!
375 //! ```rust,compile_fail
376 //! # use tracing::Level;
377 //! # fn main() {
378 //! let bad_span = span!(
379 //! Level::TRACE,
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
385 //! );
386 //! # }
387 //! ```
388 //!
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.
394 //!
395 //! For example:
396 //!
397 //! ```
398 //! # use tracing::{event, Level};
399 //! # fn main() {
400 //! let question = "the answer to the ultimate question of life, the universe, and everything";
401 //! let answer = 42;
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."
407 //! event!(
408 //! Level::DEBUG,
409 //! question.answer = answer,
410 //! question.tricky = true,
411 //! "the answer to {} is {}.", question, answer
412 //! );
413 //! # }
414 //! ```
415 //!
416 //! Specifying a formatted message in this manner does not allocate by default.
417 //!
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
426 //!
427 //! ### Shorthand Macros
428 //!
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.
435 //!
436 //! These are intended both as a shorthand, and for compatibility with the [`log`]
437 //! crate (see the next section).
438 //!
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
452 //!
453 //! ### For `log` Users
454 //!
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.
460 //!
461 //! Let's consider the `log` crate's yak-shaving example:
462 //!
463 //! ```rust,ignore
464 //! use std::{error::Error, io};
465 //! use tracing::{debug, error, info, span, warn, Level};
466 //!
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."
475 //! //
476 //! // unlike other fields, `message`'s shorthand initialization is just the string itself.
477 //! debug!(excitement = "yay!", "hello! I'm gonna shave a yak.");
478 //! if yak == 3 {
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());
484 //! } else {
485 //! debug!("yak shaved successfully");
486 //! }
487 //! Ok(())
488 //! }
489 //!
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:
493 //! //
494 //! // let span = span!(Level::TRACE, "shaving_yaks", yaks = yaks);
495 //! //
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();
500 //!
501 //! info!("shaving yaks");
502 //!
503 //! let mut yaks_shaved = 0;
504 //! for yak in 1..=yaks {
505 //! let res = shave(yak);
506 //! debug!(yak, shaved = res.is_ok());
507 //!
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!");
512 //! } else {
513 //! yaks_shaved += 1;
514 //! }
515 //! debug!(yaks_shaved);
516 //! }
517 //!
518 //! yaks_shaved
519 //! }
520 //! ```
521 //!
522 //! ## In libraries
523 //!
524 //! Libraries should link only to the `tracing` crate, and use the provided
525 //! macros to record whatever information will be useful to downstream
526 //! consumers.
527 //!
528 //! ## In executables
529 //!
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.
533 //!
534 //! This library does not contain any `Subscriber` implementations; these are
535 //! provided by [other crates](#related-crates).
536 //!
537 //! The simplest way to use a subscriber is to call the [`set_global_default`]
538 //! function:
539 //!
540 //! ```
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) {}
552 //! # }
553 //! # impl FooSubscriber {
554 //! # fn new() -> Self { FooSubscriber }
555 //! # }
556 //! # fn main() {
557 //!
558 //! let my_subscriber = FooSubscriber::new();
559 //! tracing::subscriber::set_global_default(my_subscriber)
560 //! .expect("setting tracing default failed");
561 //! # }
562 //! ```
563 //!
564 //! <div class="information">
565 //! <div class="tooltip compile_fail" style="">&#x26a0; &#xfe0f;<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.
570 //! </pre></div>
571 //!
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.
575 //!
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:
580 //!
581 //! ```rust
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) {}
592 //! # }
593 //! # impl FooSubscriber {
594 //! # fn new() -> Self { FooSubscriber }
595 //! # }
596 //! # fn main() {
597 //!
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`.
603 //! })
604 //! # }
605 //! ```
606 //!
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.
610 //!
611 //! Any trace events generated outside the context of a subscriber will not be collected.
612 //!
613 //! Once a subscriber has been set, instrumentation points may be added to the
614 //! executable using the `tracing` crate's macros.
615 //!
616 //! ## `log` Compatibility
617 //!
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.
626 //!
627 //! ### Emitting `log` Records
628 //!
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
636 //! in use.
637 //!
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.
645 //!
646 //! See [here][flags] for more details on this crate's feature flags.
647 //!
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
659 //! `tracing`.
660 //!
661 //! ### Consuming `log` Records
662 //!
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]
668 //! for details.
669 //!
670 //! [log-tracer]: https://docs.rs/tracing-log/latest/tracing_log/#convert-log-records-to-tracing-events
671 //!
672 //! ## Related Crates
673 //!
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
678 //! applications.
679 //!
680 //! In particular, the following crates are likely to be of interest:
681 //!
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.
696 //!
697 //! Additionally, there are also several third-party crates which are not
698 //! maintained by the `tokio` project. These include:
699 //!
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
708 //! framework.
709 //! - [`tracing-gelf`] implements a subscriber for exporting traces in Greylog
710 //! GELF format.
711 //! - [`tracing-coz`] provides integration with the [coz] causal profiler
712 //! (Linux-only).
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
724 //! applications.
725 //!
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!
728 //!
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
750 //!
751 //! <div class="information">
752 //! <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div>
753 //! </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>.
759 //! </pre></div>
760 //!
761 //! ## Crate Feature Flags
762 //!
763 //! The following crate feature flags are available:
764 //!
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`
769 //! or `log`.
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).
779 //!
780 //! `no_std` users may disable this feature with `default-features = false`:
781 //!
782 //! ```toml
783 //! [dependencies]
784 //! tracing = { version = "0.1.22", default-features = false }
785 //! ```
786 //!
787 //! <div class="information">
788 //! <div class="tooltip ignore" style="">ⓘ<span class="tooltiptext">Note</span></div>
789 //! </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>.
794 //! </pre></div>
795 //!
796 //! ## Supported Rust Versions
797 //!
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.
801 //!
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.
809 //!
810 //! [`log`]: https://docs.rs/log/0.4.6/log/
811 //! [span]: mod@span
812 //! [spans]: mod@span
813 //! [`Span`]: span::Span
814 //! [`in_scope`]: span::Span::in_scope
815 //! [event]: Event
816 //! [events]: Event
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")]
841 #![doc(
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/"
844 )]
845 #![warn(
846 missing_debug_implementations,
847 missing_docs,
848 rust_2018_idioms,
849 unreachable_pub,
850 bad_style,
851 const_err,
852 dead_code,
853 improper_ctypes,
854 non_shorthand_field_patterns,
855 no_mangle_generic_items,
856 overflowing_literals,
857 path_statements,
858 patterns_in_fns_without_body,
859 private_in_public,
860 unconditional_recursion,
861 unused,
862 unused_allocation,
863 unused_comparisons,
864 unused_parens,
865 while_true
866 )]
867
868 #[cfg(not(feature = "std"))]
869 extern crate alloc;
870
871 #[macro_use]
872 extern crate cfg_if;
873
874 #[cfg(feature = "log")]
875 #[doc(hidden)]
876 pub use log;
877
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)]
881 #[doc(hidden)]
882 use tracing_core::*;
883
884 #[doc(inline)]
885 pub use self::instrument::Instrument;
886 pub use self::{dispatcher::Dispatch, event::Event, field::Value, subscriber::Subscriber};
887
888 #[doc(hidden)]
889 pub use self::span::Id;
890
891 #[doc(hidden)]
892 pub use tracing_core::{
893 callsite::{self, Callsite},
894 metadata,
895 };
896 pub use tracing_core::{event, Level, Metadata};
897
898 #[doc(inline)]
899 pub use self::span::Span;
900 #[cfg(feature = "attributes")]
901 #[cfg_attr(docsrs, doc(cfg(feature = "attributes")))]
902 #[doc(inline)]
903 pub use tracing_attributes::instrument;
904
905 #[macro_use]
906 mod macros;
907
908 pub mod dispatcher;
909 pub mod field;
910 /// Attach a span to a `std::future::Future`.
911 pub mod instrument;
912 pub mod level_filters;
913 pub mod span;
914 pub(crate) mod stdlib;
915 pub mod subscriber;
916
917 #[doc(hidden)]
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;
923
924 /// Callsite implementation used by macro-generated code.
925 ///
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
931 /// without warning.
932 #[derive(Debug)]
933 pub struct MacroCallsite {
934 interest: AtomicUsize,
935 meta: &'static Metadata<'static>,
936 registration: Once,
937 }
938
939 impl MacroCallsite {
940 /// Returns a new `MacroCallsite` with the specified `Metadata`.
941 ///
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
947 /// without warning.
948 pub const fn new(meta: &'static Metadata<'static>) -> Self {
949 Self {
950 interest: AtomicUsize::new(0xDEADFACED),
951 meta,
952 registration: Once::new(),
953 }
954 }
955
956 /// Registers this callsite with the global callsite registry.
957 ///
958 /// If the callsite is already registered, this does nothing.
959 ///
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
965 /// without warning.
966 #[inline(never)]
967 // This only happens once (or if the cached interest value was corrupted).
968 #[cold]
969 pub fn register(&'static self) -> Interest {
970 self.registration
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(),
976 }
977 }
978
979 /// Returns the callsite's cached Interest, or registers it for the
980 /// first time if it has not yet been registered.
981 ///
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
987 /// without warning.
988 #[inline]
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(),
995 }
996 }
997
998 pub fn is_enabled(&self, interest: Interest) -> bool {
999 interest.is_always()
1000 || crate::dispatcher::get_default(|default| default.enabled(self.meta))
1001 }
1002
1003 #[inline]
1004 #[cfg(feature = "log")]
1005 pub fn disabled_span(&self) -> crate::Span {
1006 crate::Span::new_disabled(self.meta)
1007 }
1008
1009 #[inline]
1010 #[cfg(not(feature = "log"))]
1011 pub fn disabled_span(&self) -> crate::Span {
1012 crate::Span::none()
1013 }
1014 }
1015
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,
1021 _ => 1,
1022 };
1023 self.interest.store(interest, Ordering::SeqCst);
1024 }
1025
1026 #[inline(always)]
1027 fn metadata(&self) -> &Metadata<'static> {
1028 &self.meta
1029 }
1030 }
1031 }
1032
1033 mod sealed {
1034 pub trait Sealed {}
1035 }