|
| 1 | +## Log messages to the console |
| 2 | + |
| 3 | +[![tracing-badge]][tracing] [![tracing-subscriber-badge]][tracing-subscriber] [![cat-debugging-badge]][cat-debugging] |
| 4 | + |
| 5 | +The `tracing` crate provides macros to emit log events to a tracing subscriber. The |
| 6 | +`tracing-subscriber` crate configures where to send the events. To install the default tracing |
| 7 | +subscriber, call [`tracing_subscriber::fmt::init()`]. |
| 8 | + |
| 9 | +[`tracing_subscriber::fmt::init()`]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/fn.init.html |
| 10 | + |
| 11 | +```rust |
| 12 | +use tracing::{debug, error, info, trace, warn}; |
| 13 | + |
| 14 | +fn main() { |
| 15 | + tracing_subscriber::fmt::init(); |
| 16 | + |
| 17 | + error!("This is an error!"); |
| 18 | + warn!("This is a warning."); |
| 19 | + info!("This is an informational message."); |
| 20 | + |
| 21 | + // with the default configuration, debug! and trace! messages are not shown |
| 22 | + debug!("This is a debug message."); |
| 23 | + trace!("This is a trace message."); |
| 24 | +} |
| 25 | +``` |
| 26 | + |
| 27 | +The default log level is `INFO`. Tracing will drop events logged at lower levels. Running this code |
| 28 | +prints the following to the console: |
| 29 | + |
| 30 | +<!-- |
| 31 | + Generated using https://crates.io/crates/to-html, running: |
| 32 | + RUST_LOG=trace to-html --no-prompt "cargo run --quiet --example=tracing-console |
| 33 | +--> |
| 34 | + |
| 35 | +<pre class="terminal"><code><span style='opacity:0.67'>2024-12-01T07:56:14.778440Z</span> <span style='color:var(--red,#a00)'>ERROR</span> <span style='opacity:0.67'>tracing_console:</span> This is an error! |
| 36 | +<span style='opacity:0.67'>2024-12-01T07:56:14.778568Z</span> <span style='color:var(--yellow,#a60)'> WARN</span> <span style='opacity:0.67'>tracing_console:</span> This is a warning. |
| 37 | +<span style='opacity:0.67'>2024-12-01T07:56:14.778596Z</span> <span style='color:var(--green,#0a0)'> INFO</span> <span style='opacity:0.67'>tracing_console:</span> This is an informational message. |
| 38 | +</code></pre> |
| 39 | + |
| 40 | +To configure a more verbose default level, set the `RUST_LOG` environment variable: |
| 41 | + |
| 42 | +```shell |
| 43 | +RUST_LOG=trace cargo run --example log-debug |
| 44 | +``` |
| 45 | + |
| 46 | +Cargo prints these following extra lines in addition to the ones above: |
| 47 | + |
| 48 | +<pre class="terminal"><code><span style='opacity:0.67'>2024-12-01T07:56:14.778613Z</span> <span style='color:var(--blue,#00a)'>DEBUG</span> <span style='opacity:0.67'>tracing_console:</span> This is a debug message. |
| 49 | +<span style='opacity:0.67'>2024-12-01T07:56:14.778640Z</span> <span style='color:var(--magenta,#a0a)'>TRACE</span> <span style='opacity:0.67'>tracing_console:</span> This is a trace message. |
| 50 | +</code></pre> |
0 commit comments