Chuyển đến nội dung

Bài 5 · Getting Started

Axum Project Layout, Logging and Configuration

Organise an Axum codebase into modules, add structured logging with tracing and RUST_LOG filters, and keep configuration in one typed struct that fails fast.

A single main.rs is perfect for a first server and painful for a tenth endpoint. Axum does not impose a structure, which is a freedom and a risk. This lesson shows a layout that scales from a prototype to a real service, and then covers the two cross-cutting concerns you want from day one: logging and configuration.

None of this is Axum-specific magic. It is plain Rust modules and a couple of well-known crates, arranged so that handlers, routes, state and errors each have an obvious home.

A layout that scales

TEXT
hello-axum/
  Cargo.toml
  src/
    main.rs          # start-up only: config, logging, bind, serve
    lib.rs           # exports app() so tests can use it
    config.rs        # typed settings read from the environment
    state.rs         # AppState (database pool, config, caches)
    error.rs         # AppError and IntoResponse for it
    routes/
      mod.rs         # builds the top-level Router
      health.rs      # /health
      users.rs       # /users routes and handlers
      notes.rs       # /notes routes and handlers
  tests/
    api.rs           # integration tests that call app()

Guidelines that make this work:

  • main.rs stays tiny. It reads config, starts logging, builds state, calls app(state) and serves. Everything else lives in the library, which is easy to test.
  • One module per resource. A users.rs file owns the user handlers and exposes pub fn router() -> Router<AppState>. The top-level router merges them (see nesting and merging).
  • State and errors are shared modules. Handlers import AppState and AppError rather than inventing their own.
  • Keep handlers thin. Parse input with extractors, call a function that holds the logic, return a value. Logic that is separate from HTTP is easy to unit test.

A routes/users.rs file in this style looks like this:

Rust
use axum::{extract::Path, routing::get, Json, Router};

use crate::state::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/", get(list_users))
        .route("/{id}", get(get_user))
}

async fn list_users() -> Json<Vec<String>> {
    Json(vec!["ada".into(), "grace".into()])
}

async fn get_user(Path(id): Path<u32>) -> String {
    format!("user {id}")
}

and routes/mod.rs assembles the pieces:

Rust
use axum::Router;

use crate::state::AppState;

mod health;
mod users;

pub fn app(state: AppState) -> Router {
    Router::new()
        .merge(health::router())
        .nest("/users", users::router())
        .with_state(state)
}

Modules in miniature

The layout is only Rust's module system. This runnable model puts a router, handlers and an error type in nested modules inside one file, the way they would sit in separate files. It also shows why pub fn router() per module is a convenient seam.

Rust Stand-in: modules per resource, merged by a top-level router

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.

Structured logging with tracing

println! does not scale: no levels, no timestamps, no filtering, no structure. The Rust web ecosystem uses the tracing crate. You emit events and spans with macros, and a subscriber decides how they are printed or shipped.

Rust
use tracing::{info, warn, instrument};

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "hello_axum=debug,tower_http=debug".into()),
        )
        .init();

    info!("starting up");
    // ...
}

#[instrument]
async fn find_user(id: u32) -> Option<String> {
    warn!(user_id = id, "lookup is slow");
    None
}

#[instrument] wraps a function in a span carrying its arguments, so every log line inside is tagged with the user id. Control verbosity at run time:

Terminal
RUST_LOG=info cargo run
RUST_LOG=hello_axum=debug,tower_http=trace cargo run

The syntax is target=level separated by commas. Levels from quiet to noisy: error, warn, info, debug, trace. In middleware you will add TraceLayer from tower-http, which logs every request and response automatically.

Here is a runnable model of the filter rule so you can see how RUST_LOG directives decide what prints:

Rust Stand-in: a RUST_LOG-style level filter

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.

One typed config struct

Gather every setting into a Config loaded once at start-up and stored in the application state. A typed struct beats scattered env::var calls: a missing or invalid variable stops the process with a clear message instead of failing later at 3 a.m. The environment example in setting up a project is the pattern; crates such as config or envy automate it, but a hand-written from_env() is often enough.

Never commit secrets. Keep a .env.example file with placeholder values, load the real .env only in development, and let production inject variables through the platform.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What should main.rs contain in a well-organised Axum service?

    Keeping main small and putting the app in a library makes the service testable and easy to navigate.
  2. 2. What does RUST_LOG=warn,my_app=debug do with tracing's EnvFilter?

    A bare level sets the default; target=level overrides it for that module path.
  3. 3. What does #[instrument] add to a function?

    The attribute creates a span around each call, so events inside carry its fields.
  4. 4. Why load configuration once into a typed struct?

    Validating early avoids runtime surprises and removes stringly-typed lookups from handlers.

Summary

  • Keep main.rs tiny, put the app in a library, and use one module per resource with a router() function.
  • tracing plus EnvFilter gives levels, spans and run-time filtering through RUST_LOG.
  • Centralise settings in a typed config struct, validate at start-up, never commit secrets.

Next: Routing Basics

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.