axum

Learn about monitoring your axum application with Sentry.

The Sentry SDK offers a middleware for the axum framework that supports:

  • Reporting errors and panics with the correct request correlation.
  • Starting a transaction for each request-response cycle.

The integration actually supports any crate based on tower, not just axum.

To add Sentry with the axum integration to your Rust project, just add a new dependency to your Cargo.toml:

Cargo.toml
Copied
[dependencies]
axum = "0.8.4"
tower = "0.5.2"
tokio = { version = "1.45.0", features = ["full"] }
sentry = { version = "0.38.1", features = ["tower-axum-matched-path"] }

Initialize and configure the Sentry client. This will enable a set of default integrations, such as panic reporting. Then, initialize axum with the Sentry middleware.

main.rs
Copied
use axum::{body::Body, http::Request, routing::get, Router};
use sentry::integrations::tower::{NewSentryLayer, SentryHttpLayer};
use std::io;
use tower::ServiceBuilder;

async fn failing() -> () {
    panic!("Everything is on fire!")
}

fn main() -> io::Result<()> {
    let _guard = sentry::init((
        "https://examplePublicKey@o0.ingest.sentry.io/0",
        sentry::ClientOptions {
            release: sentry::release_name!(),
            // Capture all traces and spans. Set to a lower value in production
            traces_sample_rate: 1.0,
            // Capture user IPs and potentially sensitive headers when using HTTP server integrations
            // see https://docs.sentry.io/platforms/rust/data-management/data-collected for more info
            send_default_pii: true,
            ..Default::default()
        },
    ));

    let app = Router::new().route("/", get(failing)).layer(
        ServiceBuilder::new()
            // If you're binding the layers directly on the `Router`, bind them in the opposite order, otherwise you might run into a memory leak
            .layer(NewSentryLayer::<Request<Body>>::new_from_top()) // Bind a new Hub per request, to ensure correct error <> request correlation
            .layer(SentryHttpLayer::new().enable_transaction()), // Start a transaction (Sentry root span) for each request
    );

    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?
        .block_on(async {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:3001")
                .await
                .unwrap();
            axum::serve(listener, app.into_make_service())
                .await
                .unwrap();
        });

    Ok(())
}

The snippet above sets up a service that always panics, so you can test that everything is working as soon as you set it up.

Send a request to the application. The panic will be captured by Sentry.

Copied
curl http://localhost:3001/

To view and resolve the recorded error, log into sentry.io and select your project. Clicking on the error's title will open a page where you can see detailed information and mark it as resolved.

Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").