Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 132 ยท Testing and Tooling

Debugging, Logging and Diagnostics

Debug Rust with dbg!, Debug output, readable panics and backtraces, assert and debug_assert, a hand-made logger, rust-gdb, lldb and Miri.

Every program misbehaves at some point. In Rust, the compiler removes whole families of bugs before you ever run the code, but logic errors, wrong assumptions and surprising data still slip through. This lesson collects the everyday tools for finding them: printing values quickly with dbg!, reading panic messages and backtraces, checking your assumptions with assert!, adding logging, and reaching for a real debugger when printing is not enough.

Most of the time you will not need a debugger at all. Rust's type system and its habit of failing loudly (a panic with a file name and a line number) mean that a few well-placed prints usually point at the problem. We start with the cheapest tool and work toward the heavy ones.

Printing values with dbg!

You already know println!("{:?}", value). The dbg! macro is a sharper version made for debugging. It prints to standard error, so it never mixes with your program's real output, and it shows the file, the line, the source text of the expression and its value, pretty-printed with {:#?}. Best of all, it returns the value, so you can wrap it around part of an expression without restructuring the code.

Rust dbg! returns its argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The run prints the area = 20 line on standard output, and the three [main.rs:LINE:COL] expression = value lines on standard error. In our editor both streams appear in the output panel; on your own machine you can separate them with 2>debug.log.

Two details trip people up:

  • dbg!(x) moves x when x is not Copy, because it takes the value by value and hands it back. To keep using a String or a Vec afterwards, write dbg!(&x) as above.
  • In a release build dbg! still prints. It is meant to be temporary: search your project for dbg! before you commit. Clippy has a lint for it, clippy::dbg_macro, which you will meet in Clippy, rustfmt and Code Quality.

Use dbg! on the value that is wrong and on the value you believe feeds it. Two or three prints that bracket the bug beat a dozen scattered ones.

Making your types printable with Debug

dbg! and {:?} need the Debug trait. For your own types, a #[derive(Debug)] writes the implementation for you, and {:#?} spreads the result over several lines with indentation, which is far easier to read for nested data.

Rust Debug and pretty Debug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Derive Debug on almost every type you write. It costs nothing at run time unless you print, and it is what makes assert_eq! failures, panic messages and dbg! useful. If a field type does not implement Debug, the compiler stops you with error[E0277]: ... doesn't implement 'Debug' and a hint to derive it.

When the derived output is too noisy, or when a type holds a secret such as a password, implement Debug by hand with f.debug_struct("Account").field("id", &self.id).finish(). Leaving a field out of that list is the standard way to keep it out of logs. See Display and From for the sibling trait you use for user-facing text.

Reading a panic

A panic is Rust's way of saying "this should never happen, and I cannot continue". It prints a message and, by default, unwinds the stack and ends the thread. Because the main thread ends, the program exits with code 101. The message already contains most of what you need: the thread, the file, the line and column, and the reason.

Rust An out-of-bounds index (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first call prints 20. The second one panics with a message like index out of bounds: the len is 3 but the index is 3, pointing at main.rs:2:5, the line inside pick where the index operation happens. Note the line: it is where the panic occurred, not where the bad index was chosen. To find the caller you need a backtrace.

Backtraces

Set the environment variable RUST_BACKTRACE=1 before running and Rust prints the chain of function calls that led to the panic. RUST_BACKTRACE=full adds more detail. In your terminal that looks like this (read-only example, the exact frames depend on your platform):

Terminal
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at src/main.rs:2:5:
index out of bounds: the len is 3 but the index is 3
stack backtrace:
   0: rust_begin_unwind
   1: core::panicking::panic_fmt
   2: core::panicking::panic_bounds_check
   3: demo::pick
             at ./src/main.rs:2:5
   4: demo::main
             at ./src/main.rs:8:20

Read it from the top and skip the frames that belong to std and core. The first frame with a path into your code is the panic site (demo::pick), and the next one down is the caller that passed the bad value (demo::main, line 8). For useful line numbers the program needs debug information, which cargo run (the debug profile) has by default.

Panic messages from unwrap and expect

unwrap() on a None or an Err panics with a generic message. expect("...") lets you add the reason, which is the single most useful habit for debugging panics later.

Rust unwrap versus expect (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The panic text reads the port table should list ssh. Compare it with a bare unwrap(), which would only say called 'Option::unwrap()' on a 'None' value. A good expect message states what you expected to be true, not what went wrong. See Panic for when panicking is the right choice at all.

Checking assumptions with assert!

An assertion states something that must be true. If it is not, the program panics right there, close to the real mistake, instead of failing mysteriously later. Rust gives you a family of them:

Macro Checks Present in release builds?
assert!(cond) cond is true yes
assert_eq!(a, b) / assert_ne!(a, b) equality, printing both sides on failure yes
debug_assert!(cond) same as assert! no, only with debug assertions
debug_assert_eq!, debug_assert_ne! same as above no
unreachable!(), todo!(), unimplemented!() marks code that must not run yes

All of them accept an optional format string after the condition, so a failure explains itself: assert!(len > 0, "buffer for {name} is empty").

Rust assert_eq with a message (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The second assertion fails because integer division rounds down: 3 / 2 is 1. The panic prints assertion `left == right` failed: rounding of 2 values, then left: 1 and right: 2. Seeing both values side by side is why you should prefer assert_eq!(a, b) over assert!(a == b).

debug_assert! and the debug profile

debug_assert! is checked only when debug assertions are enabled, which is the default for the dev profile and off in --release. Use it for checks that are too slow to leave on in production, such as verifying that a vector is still sorted after every insert. Our editor compiles with debug assertions on, so you can see them fire. You can ask the compiler which mode you are in with cfg!(debug_assertions):

Rust Debug-only checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program prints true, the sorted list [0, 1, 5, 6, 9], and then the last call panics: list lost its order. In a release build, the same program would print a silently wrong list. That is the trade: debug assertions find bugs during development, but they are not a substitute for validating input that comes from outside.

Another debug-only behaviour is integer overflow. In debug builds 255u8 + 1 panics with attempt to add with overflow, while a release build wraps around silently. Use checked_add, wrapping_add or saturating_add when you want a specific behaviour; Integer Overflow covers them all.

A tiny logger of your own

For anything longer than a quick investigation, printing with println! becomes noise. Logging adds levels (error, warn, info, debug, trace) so you can keep detailed messages in the code and switch them on only when needed.

Real projects use two crates. They are read-only here because our editor has no external crates:

TOML
# Cargo.toml (read-only: needs crates.io)
[dependencies]
log = "0.4"
env_logger = "0.11"
Rust
// main.rs (read-only: needs the log and env_logger crates)
use log::{debug, info, warn};

fn main() {
    env_logger::init(); // level comes from the RUST_LOG variable
    info!("starting");
    debug!("config loaded: {} entries", 12);
    warn!("cache is cold");
}
Terminal
$ RUST_LOG=debug cargo run

The log crate is a facade: library authors call info! and friends, and the application chooses one backend such as env_logger. The newer tracing crate adds spans, which record a stretch of time with context (a request id, a user), and is the usual choice for async servers.

You can build the core idea with the standard library in a few lines. This stand-in uses a global atomic for the level and a macro so the message is only formatted when it will be printed:

Rust A hand-written leveled logger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first Debug message is skipped and its arguments are never evaluated, so the costly summary does not run. After raising the level, the same line prints both the helper's note and the message. Real logging crates use exactly this trick, which is why a disabled debug! call costs almost nothing. The macro machinery is explained in Declarative Macros.

Taking control of panics

Sometimes you want a panic to say more, for example to add the application version to every crash report. A panic hook replaces the default message printer. It runs when a panic starts, before unwinding.

Rust A custom panic hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

catch_unwind stops the unwinding at that point and returns an Err. It exists for boundaries like a thread pool or a foreign-function call; it is not Rust's version of exceptions. Use Result for expected failures (Error Handling) and keep panics for bugs. Code compiled with panic = "abort" in the profile never unwinds, and catch_unwind cannot catch anything there.

When prints are not enough

A real debugger

Rust ships wrappers around the standard debuggers: rust-gdb and rust-lldb (installed with rustup) load pretty-printers so a Vec or a String shows its contents, not raw pointers. You set a breakpoint, run, and inspect locals:

Terminal
$ cargo build
$ rust-lldb target/debug/demo
(lldb) breakpoint set --file main.rs --line 12
(lldb) run
(lldb) frame variable
(lldb) continue

Editors do the same with a click. VS Code with the CodeLLDB extension and RustRover both give you breakpoints and a variables panel. Use the debug profile: release builds inline functions and reorder code, so the debugger jumps around and many variables are "optimized out".

Miri for undefined behaviour

If you write unsafe code (Unsafe Rust), a normal test can pass while the code has undefined behaviour. Miri is an interpreter for Rust's mid-level IR that runs your tests and reports reads of uninitialized memory, use after free, data races and violations of the aliasing rules:

Terminal
$ rustup +nightly component add miri
$ cargo +nightly miri test

Miri is slow, so run it on the small tests that exercise your unsafe code, not on the whole suite. We come back to it in Building Data Structures with Unsafe.

Looking at what macros produce

When a macro_rules! or derive macro gives a confusing error, cargo expand (a third-party subcommand) prints the code after expansion. cargo rustc -- -Zunpretty=expanded does the same on nightly. Seeing the generated code usually explains the error immediately.

A debugging routine that works

  1. Reproduce the problem with the smallest input. A failing test is best, because it stays as a regression guard (Testing in Rust).
  2. Read the whole error, including the line and the left/right values. Compiler errors and panics are unusually specific.
  3. Bracket the bug with dbg! or assertions. Check the input of a suspicious function, then its output.
  4. Form one hypothesis and test it, rather than changing several things at once.
  5. Fix the cause, keep the test, and remove the dbg! calls.

Never leave dbg! or println! of secrets (tokens, passwords, personal data) in code that runs on a server. Logs are copied, shipped and stored for years.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does dbg! write its output, and what does it return?

    dbg! prints to standard error with file, line and expression text, then hands the value back so it can be used inside a larger expression.
  2. 2. You write dbg!(name); where name is a String, then use name on the next line. What happens?

    dbg! takes its argument by value and returns it. A non-Copy value is moved into the macro, so borrow it with &name if you still need it.
  3. 3. What is the difference between assert! and debug_assert!?

    assert! is always compiled in. debug_assert! disappears from builds without debug assertions, so use it for checks that would be too slow in production.
  4. 4. In a backtrace, which frame usually tells you who passed the bad value to the function that panicked?

    The first frame in your own code is where the panic happened. The frame below it is the caller, which is usually where the wrong value came from.
  5. 5. Why is catch_unwind not a replacement for Result?

    Use Result for failures you expect. catch_unwind is for boundaries such as thread pools and FFI, and it does nothing when panics abort.

Summary

  • dbg!(expr) prints the source text, file, line and value to standard error and returns the value; pass &x to avoid moving.
  • Derive Debug on your types and use {:#?} for readable multi-line output.
  • A panic message names the file and line of the failure; RUST_BACKTRACE=1 shows the call chain, and expect messages should state what you expected.
  • assert!, assert_eq! and friends document and enforce assumptions; debug_assert! and integer overflow checks exist only in debug builds.
  • Leveled logging (log, tracing) keeps diagnostics in the code at almost no cost when disabled; a macro can show the idea with only std.
  • rust-gdb, rust-lldb and Miri cover what prints cannot: stepping through code and finding undefined behaviour.

Next: Clippy, rustfmt and Code Quality