Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 132 ยท Projects

Building CLI Tools: Arguments, Logging and Errors

Build a command-line tool in Rust: parse subcommands and flags, add leveled logging, wrap errors with context and return proper exit codes, then map it to clap, tracing and anyhow.

Command-line tools are where Rust shines: one small static binary, instant start-up, no runtime to install. ripgrep, fd, bat and cargo itself are all Rust CLIs. A good CLI, though, is more than a main that reads a few arguments. It parses flags and subcommands, reports mistakes in plain language, writes diagnostics to the right place, can be made chatty or quiet, and tells the shell whether it succeeded through its exit code.

In real projects three crates do most of this work: clap for arguments, tracing (or log) for logging, and anyhow for application errors. The editor here only has the standard library, so this lesson first builds a small stand-in for each one. That way you learn what the crates actually do, and the code you write against the real crates later will make sense. At the end you will see the same program written with the real thing. If you have not built a command-line program before, the to-do project and the grep clone are good warm-ups, and Environment, Processes and Signals covers std::env::args and exit codes in more detail.

The shape of a CLI program

Well-structured tools keep main tiny and put all the logic in functions that can be tested without a terminal:

flowchart LR
    A["argv"] --> B["parse<br/>(flags, subcommand)"]
    B -->|usage error| E["message on stderr<br/>exit code 2"]
    B -->|ok| C["run(cli)"]
    C -->|Ok| D["exit code 0"]
    C -->|Err| F["error chain on stderr<br/>exit code 1"]

Parsing and running are separate steps, and each failure maps to a distinct exit code.

A few conventions make a tool feel professional, and users (and scripts) rely on them:

  • Output for data, messages for people. Results go to stdout so they can be piped; diagnostics, progress and errors go to stderr.
  • Exit codes. 0 means success, 1 a runtime failure, 2 a usage mistake such as a bad flag. Some tools define more.
  • --help and --version always work and exit with 0.
  • -- ends flag parsing, so a file called -weird-name can still be passed.
  • Never panic on user mistakes. A missing file is an error to report, not a bug.

Parsing arguments: a tiny clap

clap is declarative: you describe the flags, and it parses and builds --help. The same idea works in a few dozen lines. We describe each subcommand's flags in a table, a generic function turns the raw arguments into Matches (the flags that were given plus the positional words), and each subcommand converts the matches into a typed value. The global -v and -q flags are handled before the subcommand name, as in tool -v -v add ....

The example models a pantry tool with three subcommands (add, list, remove). It supports --qty 3, --qty=3, and -n 3, rejects unknown flags, and uses -- to end flag parsing. The errors are an enum with a readable Display, and each error knows its exit code.

Rust A declarative argument parser

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.

Study how the pieces fit. The generic parse_flags knows nothing about pantries, so each new subcommand costs only a flag table and a few lines of conversion. Values are validated at the edge: the string "many" becomes a typed error before any business logic runs, and everything inside the program works with a u32. clap adds what this stand-in lacks: grouped short flags such as -vv, --help text generated from the declaration, value enums, environment-variable fallbacks, shell completions and "did you mean" suggestions.

The real thing with clap

With clap and its derive feature, the entire parser above becomes a declaration. This snippet is read-only because the editor has no crates:

Rust
use clap::{Parser, Subcommand};

/// A tiny pantry manager.
#[derive(Parser)]
#[command(version, about)]
struct Cli {
    /// Increase log detail (-v, -vv); -q for less.
    #[arg(short, long, action = clap::ArgAction::Count, global = true)]
    verbose: u8,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Add an item to the pantry.
    Add {
        name: String,
        #[arg(short = 'n', long, default_value_t = 1)]
        qty: u32,
    },
    /// Show what is stored.
    List {
        #[arg(short, long)]
        all: bool,
    },
    /// Remove an item.
    Remove { name: String },
}

fn main() {
    let cli = Cli::parse(); // prints help or errors and exits for you
    // ...
}

Cli::parse() exits the process on --help, --version and usage errors (with exit code 2, the same convention as our stand-in). Use Cli::try_parse() if you want the error value instead, which is handy in tests.

Leveled logging

println! is fine for results, but diagnostics need levels: errors and warnings are always interesting, informational messages are often wanted, and debug/trace messages are for when something is wrong. The Rust ecosystem splits this in two, the same way as the serializers in the previous lesson on data formats:

  • A facade (log, or tracing) gives libraries macros like info! and debug! that do nothing until someone installs a backend.
  • A backend (env_logger, tracing-subscriber) decides where messages go, how they are formatted and which levels are kept.

Because libraries only depend on the facade, an application chooses the output once, in main. The facade is built from a global maximum level (an atomic number), a global logger set exactly once, and macros that capture the module path and a lazily formatted message. The key trick is format_args!: it does not build a String. It packages the pieces, and formatting happens only if a logger actually prints the message. A disabled debug! call therefore costs one comparison and never runs the Display code of its arguments, which the example proves with a counter.

Rust A log facade with a global level

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.

Real logs also carry timestamps, thread ids and structured fields (info!(user_id = 7, "login ok")), which tracing supports natively and which log aggregation systems can search. tracing additionally has spans, regions of time with context that every message inside inherits, which is how asynchronous services follow one request across many tasks. The usual wiring in main is a single line, and the verbosity flags map to levels:

Rust
fn init_logging(verbosity: i32) {
    let level = match verbosity {
        i32::MIN..=-1 => tracing::Level::ERROR,
        0 => tracing::Level::WARN,
        1 => tracing::Level::INFO,
        2 => tracing::Level::DEBUG,
        _ => tracing::Level::TRACE,
    };
    tracing_subscriber::fmt()
        .with_max_level(level)
        .with_writer(std::io::stderr) // logs never pollute stdout
        .init();
}

With env_logger or tracing_subscriber::EnvFilter users can also override levels per module with the RUST_LOG environment variable, for example RUST_LOG=mytool=debug,hyper=warn.

Log to stderr, not stdout. A CLI whose stdout is piped into another program (tool list | sort) must not mix log lines into the data.

Errors with context

A raw error like No such file or directory (os error 2) is useless without knowing which file and what you were doing. The fix is to wrap each error with a sentence about the operation as it travels up the call stack, keeping the original as its source. At the top level the program prints the whole chain. This is what the anyhow crate does with .context("..."), and it is short enough to build.

The key ingredients are an application error type that implements std::error::Error (see Custom Error Types and Designing Error Types), a Context trait implemented for every Result<T, E: Error> and for Option<T>, and a printer that walks source(). The example also shows how to look through the chain with downcast_ref to pick an exit code from the original io::ErrorKind.

Rust Error context and chains, anyhow style

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.

Each layer added only what it knew: the parser knows which text was bad, port_from_settings knows it was reading a setting, and the top-level function knows it was loading the configuration. The io error at the bottom is untouched, so code that needs to react to it (retry, exit code, special message) can still find it with downcast_ref.

Exit codes: from main to the shell

A main that returns Result<(), E> prints the error with Debug (Error: ...) and exits with code 1. That is fine for scripts, but a polished tool builds the message itself. Return std::process::ExitCode, which lets you choose the number while still running destructors (unlike process::exit, which skips them):

Rust
use std::process::ExitCode;

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("{}", report(&e));
            match io_kind(&e) {
                Some(std::io::ErrorKind::NotFound) => ExitCode::from(66),
                Some(std::io::ErrorKind::PermissionDenied) => ExitCode::from(77),
                _ => ExitCode::FAILURE, // 1
            }
        }
    }
}

The numbers 66 (EX_NOINPUT) and 77 (EX_NOPERM) come from the BSD sysexits.h convention. You do not have to use them, but documenting your codes is kind to the people who script your tool.

The same program with the real crates

Put together, a main.rs using the ecosystem crates reads like this (read-only). Compare each line with the stand-ins above:

Rust
use anyhow::{Context, Result};
use clap::Parser;

#[derive(Parser)]
#[command(version, about)]
struct Cli {
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,
    /// Settings file to read.
    #[arg(long, default_value = "pantry.conf")]
    config: std::path::PathBuf,
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    tracing_subscriber::fmt()
        .with_max_level(match cli.verbose {
            0 => tracing::Level::WARN,
            1 => tracing::Level::INFO,
            _ => tracing::Level::DEBUG,
        })
        .with_writer(std::io::stderr)
        .init();

    let text = std::fs::read_to_string(&cli.config)
        .with_context(|| format!("cannot read {}", cli.config.display()))?;
    tracing::info!(bytes = text.len(), "settings loaded");
    Ok(()) // an Err here prints "Error: ... Caused by: ..." and exits with 1
}

Use anyhow in applications where you only report errors, and thiserror in libraries where callers need to match on error variants.

Testing the tool

Because parse is a pure function and the work happens in run, tests need no terminal. Pass &[&str] to parse and compare with the expected Cli. For output, have run write to a &mut impl std::io::Write instead of calling println!: tests pass a Vec<u8>, and main passes stdout().lock(). For end-to-end tests of the compiled binary, the assert_cmd crate runs it as a child process and checks its stdout, stderr and exit code. See Testing and Test Patterns for the general techniques.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should log messages and error reports go in a CLI whose output may be piped into another program?

    stdout carries the program's results. stderr is for diagnostics, so a pipeline such as tool list | sort is not polluted by messages.
  2. 2. Why does debug!("value = {}", Expensive) cost almost nothing when the level is disabled?

    format_args! creates a lightweight fmt::Arguments value. The level check happens first, and the Display code only runs when the message is actually written.
  3. 3. What is the purpose of wrapping an error with .context("...") as it moves up the call stack?

    The context says what the program was doing; the original error stays reachable through source(), so the final report can print the whole chain and code can still downcast to the root cause.
  4. 4. What does the argument -- mean to most command-line parsers?

    -- ends flag parsing, which lets users pass values like a file named -weird-name. A single - conventionally means standard input.

Summary

  • Keep main small: parse arguments, call run, translate the result into an exit code. Logic lives in testable functions.
  • Results go to stdout, diagnostics to stderr; use exit code 0 for success, 1 for failures and 2 for usage errors, and return std::process::ExitCode from main.
  • A declarative parser (flag tables, typed conversion at the edge) is what clap generates from #[derive(Parser)].
  • A logging facade is a global max level, a global logger and macros built on format_args!, so disabled levels cost almost nothing; applications install a backend such as tracing-subscriber once.
  • Wrap errors with context as they bubble up, keep the original as source(), and print the chain at the top; anyhow does this in applications and thiserror fits libraries.
  • Test parsing as pure functions and have run write to a generic Write so output can be captured.

Next: Project: Text Adventure Engine