---
title: Honeybadger for Rust
description: Honeybadger monitors your Rust applications for errors and panics so that you can fix them wicked fast.
url: https://docs.honeybadger.io/lib/rust/
---

**Typical installation time:** \~5 minutes

Hi there! You’ve found Honeybadger’s guide to **Rust error tracking and monitoring**. Once installed, Honeybadger will automatically report panics in your Rust application, along with any errors and events you send it.

## Getting started

[Source code](https://github.com/honeybadger-io/honeybadger-rust) • [API docs](https://docs.rs/honeybadger) • [Examples](https://github.com/honeybadger-io/honeybadger-rust/tree/main/examples)

### Installation

Add `honeybadger` to your `Cargo.toml`:

```toml
[dependencies]
honeybadger = "0.5"
serde_json = "1"
```

You need `serde_json` in your own `Cargo.toml` because context and event values are `serde_json::Value`, usually built with the `json!` macro.

Upgrading from versions 0.1–0.2

Versions 0.1–0.2 of the `honeybadger` crate are a separate, community-maintained project. The official SDK starts at version 0.5.0 and has a different API. If you’re upgrading from 0.1–0.2, you’ll need to update your integration code.

### Initializing

Initialize Honeybadger near the top of `main`. Configure your [API key](https://docs.honeybadger.io/guides/projects/#api-keys), or set it in the `HONEYBADGER_API_KEY` environment variable:

* US

  ```rust
  fn main() {
      let _guard = honeybadger::init(
          honeybadger::Config::builder()
              .api_key("PROJECT_API_KEY") // or set HONEYBADGER_API_KEY
              .env("production")
              .build()
              .unwrap(),
      )
      .unwrap();


      // ... your application ...
  }
  ```

* EU

  Set the endpoint in code, as below, or with the `HONEYBADGER_ENDPOINT` environment variable.

  ```rust
  fn main() {
      let _guard = honeybadger::init(
          honeybadger::Config::builder()
              .api_key("PROJECT_API_KEY") // or set HONEYBADGER_API_KEY
              .endpoint("https://eu-api.honeybadger.io")
              .env("production")
              .build()
              .unwrap(),
      )
      .unwrap();


      // ... your application ...
  }
  ```

`init` returns a `Guard`. Keep it for the lifetime of your program by binding it to a variable, like `_guard` above. When the guard is dropped, Honeybadger sends any queued errors and events, waiting up to 5 seconds, and stops reporting. If you write `let _ = honeybadger::init(...)`, the guard is dropped immediately and nothing is sent.

By default, the `development` and `test` environments don’t report. See [Development environments](https://docs.honeybadger.io/lib/rust/#development-environments).

### Reporting panics

Once initialized, Honeybadger reports panics automatically, including under `panic = "abort"`. Unlike other reports, a panic report is sent right away, on the panicking thread, with a 5-second timeout. Any panic hook you installed before `init` still runs. To turn automatic panic reporting off, set `install_panic_hook(false)` on the config builder.

### Reporting errors

Any error that implements [`std::error::Error`](https://doc.rust-lang.org/std/error/trait.Error.html) can be reported with `honeybadger::notify`. Its `source()` chain (up to five errors) becomes the cause list in Honeybadger, and a backtrace is captured at the call site:

```rust
if let Err(e) = do_work() {
    honeybadger::notify(&e);
}
```

If your error is a `Box<dyn Error>` or an `anyhow::Error`, call `honeybadger::notify(&*e)` instead.

`notify` doesn’t wait on the network: it builds the report on your thread, then sends it in the background. It never returns an error. Delivery problems are logged with the `log` crate (see [Troubleshooting](https://docs.honeybadger.io/lib/rust/#troubleshooting)).

### Reporting errors without an error value

To report something without an error value, build a `Notice` with a class and message and send it with `notify_notice`:

```rust
honeybadger::notify_notice(
    honeybadger::Notice::message("BillingAlert", "payment gateway is down")
        .tags(["billing"])
        .fingerprint("billing-alerts"),
);
```

`Notice::message` doesn’t capture a backtrace, so by default Honeybadger groups these reports by class and message. When you have an error value, use `Notice::from_error(&e)` to include its causes and capture a backtrace.

## Adding context to errors

Honeybadger can attach key/value context to your error reports. You can add it to a single error ([local context](https://docs.honeybadger.io/lib/rust/#local-context)), to every error ([global context](https://docs.honeybadger.io/lib/rust/#global-context)), or to every error in a request ([per-request context](https://docs.honeybadger.io/lib/rust/#per-request-context)).

### Local context

Put request-specific data directly on the error report, so another request can’t overwrite it:

```rust
use serde_json::json;


honeybadger::notify_notice(
    honeybadger::Notice::from_error(&e)
        .context([("user_id", json!(123)), ("request_id", json!("req-9"))]),
);
```

Honeybadger uses a `request_id` context key as the error’s correlation ID.

### Identifying users

To track which users encountered each error, add a user identifier and/or email to the error’s context:

```rust
use serde_json::json;


honeybadger::notify_notice(
    honeybadger::Notice::from_error(&e).context([
        ("user_id", json!(user.id)),
        ("user_email", json!("user@example.com")),
    ]),
);
```

[Learn more about context data in Honeybadger](https://docs.honeybadger.io/guides/errors/#context-data)

### Global context

Use `honeybadger::context` for values that apply to your whole program, such as the region or release channel. They’re sent with every error reported after the call:

```rust
use serde_json::json;


honeybadger::context([("region", json!("us-east-1"))]);
```

To remove a key, set it to `serde_json::Value::Null`. When local and global context set the same key, the local value wins. `honeybadger::clear_context()` clears the global context, along with the breadcrumbs, event context, and request ID.

Global context is shared across requests

Global context is shared by every thread and task in your program. In a concurrent server, one request can overwrite another’s values, so an error may show the wrong user. Put request data on the error itself ([local context](https://docs.honeybadger.io/lib/rust/#local-context)), or use [per-request context](https://docs.honeybadger.io/lib/rust/#per-request-context).

### Per-request context

With the `tokio` feature enabled, wrap each request in `honeybadger::scope(...)`. Inside a scope, `context()`, `add_breadcrumb()`, `event_context()`, and `request_id()` apply only to that request, so concurrent requests can’t overwrite each other’s data:

```toml
[dependencies]
honeybadger = { version = "0.5", features = ["tokio"] }
```

```rust
use serde_json::json;


async fn handle_request(user_id: u64) {
    honeybadger::scope(async {
        honeybadger::request_id(format!("req-{user_id}"));
        honeybadger::context([("user_id", json!(user_id))]);


        // ... do the request's work. Errors and events reported in here
        // include this request's context ...
    })
    .await;
}
```

Inside a scope:

* Errors include both the global context and the request’s context, and events do the same with event context. If both set the same key, the request’s value wins.
* Errors include only the request’s breadcrumbs, not the global ones.
* Errors and events use the request’s own request ID if it set one, and the global one otherwise.
* `clear_context()` clears only that request’s data.

For synchronous handlers, use `honeybadger::scope_sync(|| { ... })` instead.

A scope doesn’t carry over into code started with `tokio::spawn`, `tokio::task::spawn_blocking`, or `std::thread::spawn`. To keep it, capture it with `honeybadger::ScopeHandle::current()` and run the new work inside `ScopeHandle::enter` (async) or `ScopeHandle::enter_sync` (a blocking closure or thread):

```rust
let scope = honeybadger::ScopeHandle::current();
tokio::task::spawn_blocking(move || {
    scope.enter_sync(|| {
        // still recorded against this request:
        honeybadger::add_breadcrumb("query ran", "query", None);
    })
});
```

You can’t do this for tasks spawned inside a third-party library, so anything reported from them uses the global context. For a complete walkthrough, see [`examples/scoped_request.rs`](https://github.com/honeybadger-io/honeybadger-rust/blob/v0.5.0/examples/scoped_request.rs).

## Breadcrumbs

Breadcrumbs record what your application was doing before an error. Add a breadcrumb with `honeybadger::add_breadcrumb`:

```rust
honeybadger::add_breadcrumb("charged customer", "billing", None);
```

The second argument is a category (`"query"`, `"ui"`, `"billing"`, `"custom"`, …) used to group related breadcrumbs in the UI. You can attach metadata as the third argument:

```rust
use serde_json::{json, Map};


let mut metadata = Map::new();
metadata.insert("order_id".into(), json!(4242));
honeybadger::add_breadcrumb("charged customer", "billing", Some(metadata));
```

Honeybadger keeps the last 40 breadcrumbs. Keep metadata flat: nested objects and arrays are replaced with `"[DEPTH]"`. Breadcrumbs are global unless you’re inside a [scope](https://docs.honeybadger.io/lib/rust/#per-request-context).

## Adding tags to errors

Add tags to categorize an error:

```rust
honeybadger::notify_notice(
    honeybadger::Notice::from_error(&e).tags(["payments", "critical"]),
);
```

## Customizing error grouping

Honeybadger [groups occurrences of the same error together](https://docs.honeybadger.io/guides/errors/#error-grouping). To control the grouping, set an explicit fingerprint:

```rust
honeybadger::notify_notice(
    honeybadger::Notice::from_error(&e).fingerprint("charge-failed"),
);
```

Occurrences with the same fingerprint are grouped into a single error, regardless of their class, message, or backtrace.

## Filtering sensitive data

Values whose keys match `filter_keys` are replaced with `"[FILTERED]"` in context and breadcrumb metadata. Keys are matched case-insensitively, and the default is `["password", "credit_card", "secret"]`. Override it on the config builder:

```rust
honeybadger::Config::builder()
    .api_key("PROJECT_API_KEY")
    .filter_keys(["password", "credit_card", "secret", "authorization"])
    .build()
    .unwrap()
```

Honeybadger filters data after your `before_notify` hooks run, so it also filters anything they add.

## Ignoring errors

Drop specific error classes without reporting them with `ignore_classes` (matched exactly against the error’s class):

```rust
honeybadger::Config::builder()
    .api_key("PROJECT_API_KEY")
    .ignore_classes(["std::io::error::Error"])
    .build()
    .unwrap()
```

For a concrete error type, the class is the type’s full path from `std::any::type_name`. For `std::io::Error`, that’s `std::io::error::Error`. For a `dyn Error`, such as the error inside a `Box<dyn Error>`, the type isn’t known, so the class is the first line of the error message. To keep a class fixed, set it with `Notice::class`:

```rust
honeybadger::notify_notice(
    honeybadger::Notice::from_error(&e).class("PaymentGatewayError"),
);
```

To filter errors in code, add a `before_notify` hook. It runs for each error report that `ignore_classes` doesn’t drop. Return `false` to drop the report. The hook can also change the report with `add_tag`, `set_class`, or `set_context`:

```rust
honeybadger::Config::builder()
    .api_key("PROJECT_API_KEY")
    .before_notify(|notice| {
        // Drop a noisy, expected error.
        !notice.error_message().contains("connection reset by peer")
    })
    .build()
    .unwrap()
```

## Sending events to Insights

You can also send structured events to [Honeybadger Insights](https://docs.honeybadger.io/guides/insights/):

```rust
use serde_json::json;


honeybadger::event("user.created", json!({ "user_id": 7, "plan": "pro" }));


// The event_type can live in the payload instead:
honeybadger::event_value(json!({ "event_type": "job.finished", "ms": 91 }));
```

The payload must be a JSON object, and an event can’t be larger than 100 kB. Honeybadger logs and drops events that break either rule. Like `notify`, `event` doesn’t wait on the network. Honeybadger sends events in batches: a batch goes out at 1000 events, after 30 seconds, or at 4.5 MB, whichever comes first.

`event` requires a `serde_json::Value`, not a struct. To send a struct, convert it with `serde_json::to_value` first:

```rust
if let Ok(payload) = serde_json::to_value(&user) {
    honeybadger::event("user.created", payload);
}
```

`filter_keys` doesn’t apply to events

Leave sensitive data out of events, including any struct you convert.

### Correlation and sampling

Set a request ID to link errors with events from the same request, and use event context to add fields to every event:

```rust
use serde_json::json;


honeybadger::request_id("req-9"); // correlates errors and events
honeybadger::event_context([("service", json!("checkout"))]); // added to every later event
```

If you set `events_sample_rate` below 100, events with the same request ID are all kept or all dropped together. Without a [scope](https://docs.honeybadger.io/lib/rust/#per-request-context), the event context and request ID are global, like `context()`. In a concurrent server, wrap each request in `scope()` or put `request_id` in each event’s payload.

### Filtering events

A `before_event` hook can change or drop each event before it’s sent. Returning `false` drops the event:

```rust
honeybadger::Config::builder()
    .api_key("PROJECT_API_KEY")
    .before_event(|event| {
        event.remove("ip_address");
        event.get("event_type").and_then(|t| t.as_str()) != Some("health_check")
    })
    .build()
    .unwrap()
```

### Event configuration

| Name | Type | Default | Environment var |
| - | - | - | - |
| `events_enabled` | bool | `true` | `HONEYBADGER_EVENTS_ENABLED` |
| `events_batch_size` | usize | `1000` | `HONEYBADGER_EVENTS_BATCH_SIZE` |
| `events_flush_interval` | Duration | 30 seconds | `HONEYBADGER_EVENTS_FLUSH_INTERVAL` |
| `events_queue_size` | usize | `10000` | `HONEYBADGER_EVENTS_QUEUE_SIZE` |
| `events_max_retries` | u32 | `3` | `HONEYBADGER_EVENTS_MAX_RETRIES` |
| `events_sample_rate` | u8 | `100` | `HONEYBADGER_EVENTS_SAMPLE_RATE` |
| `events_attach_hostname` | bool | `true` | `HONEYBADGER_EVENTS_ATTACH_HOSTNAME` |
| `events_attach_environment` | bool | `true` | `HONEYBADGER_EVENTS_ATTACH_ENVIRONMENT` |
| `before_event` | hook | none | n/a |

* **events\_flush\_interval** is set in seconds through `HONEYBADGER_EVENTS_FLUSH_INTERVAL`.
* **events\_queue\_size** limits how many events Honeybadger holds while waiting to send them, including those waiting to be retried. Past that limit, events are dropped.
* **events\_max\_retries** doesn’t count the first attempt, so the default allows four attempts.
* **events\_sample\_rate** is the percentage of events to keep, from 0 to 100.

## Flushing before exit

Call `flush` when your program exits without dropping the guard, for example with `std::process::exit`, or when you want to wait longer than the guard’s 5 seconds (see [Initializing](https://docs.honeybadger.io/lib/rust/#initializing)):

```rust
use std::time::Duration;


honeybadger::flush(Duration::from_secs(10));
```

`flush` waits until Honeybadger has finished with every queued error and event, or until the timeout runs out. It returns `false` if the timeout ran out, an event batch is waiting to be retried, or Honeybadger isn’t initialized. A `true` result doesn’t guarantee delivery; delivery failures are logged (see [Troubleshooting](https://docs.honeybadger.io/lib/rust/#troubleshooting)).

## Configuration

Build your configuration with `Config::builder()`. For options that have an environment variable, an explicit builder call wins, then the `HONEYBADGER_*` environment variable, then the default.

```rust
honeybadger::Config::builder()
    .api_key("PROJECT_API_KEY")
    .env("production")
    .build()
    .unwrap()
```

The following options are available:

| Name | Type | Default | Environment var |
| - | - | - | - |
| `api_key` | String | none | `HONEYBADGER_API_KEY` |
| `env` | String | none | `HONEYBADGER_ENV` |
| `exclude_envs` | list of strings | `["development", "test"]` | n/a |
| `enabled` | bool | derived from `env` and `exclude_envs` | `HONEYBADGER_ENABLED` |
| `endpoint` | String | `https://api.honeybadger.io` | `HONEYBADGER_ENDPOINT` |
| `root` | String | the current directory | `HONEYBADGER_ROOT` |
| `hostname` | String | the system hostname | `HONEYBADGER_HOSTNAME` |
| `revision` | String | none | `HONEYBADGER_REVISION` |
| `filter_keys` | list of strings | `["password", "credit_card", "secret"]` | n/a |
| `ignore_classes` | list of strings | `[]` | n/a |
| `breadcrumbs_enabled` | bool | `true` | n/a |
| `install_panic_hook` | bool | `true` | n/a |
| `notice_queue_size` | usize | `100` | n/a |
| `connect_timeout` | Duration | 4 seconds | n/a |
| `request_timeout` | Duration | 5 seconds | n/a |
| `before_notify` | hook | none | n/a |

* **env / exclude\_envs / enabled** control whether errors and events are reported. In an excluded environment, Honeybadger still initializes but discards what you report. Set `enabled` to turn reporting on or off regardless of the environment.
* **root** is your project root. Paths beneath it are reported as `[PROJECT_ROOT]/…`, and only files under it get source excerpts.
* **revision** attributes errors to a release; set it to your deploy’s commit SHA.

### Environment-based configuration

You can also set options with the environment variables listed in the configuration tables instead of in code. For example:

```sh
env HONEYBADGER_API_KEY=... HONEYBADGER_ENV=production ./my-app
```

Boolean variables accept `true`, `1`, or `yes`, in lowercase. Any other value, including `TRUE`, is read as false.

### Development environments

Honeybadger **does not** report errors or events from the `development` and `test` environments unless you explicitly enable reporting:

```rust
honeybadger::Config::builder()
    .api_key("PROJECT_API_KEY")
    .env("development")
    .enabled(true) // or set HONEYBADGER_ENABLED=true
    .build()
    .unwrap()
```

To change which environments are excluded, set `exclude_envs`.

## Troubleshooting

If errors aren’t showing up in Honeybadger, check the logs. Honeybadger logs delivery problems, such as a bad API key or a network failure, with the [`log`](https://docs.rs/log) crate. To see them, add a `log` backend such as [`env_logger`](https://docs.rs/env_logger), call `env_logger::init()` at the start of `main`, and turn on debug logging:

```sh
RUST_LOG=honeybadger=debug cargo run
```

If `init` fails at startup with a missing API key error, set your API key in code or with the `HONEYBADGER_API_KEY` environment variable.

How Honeybadger handles API responses:

* **429 and 503**: Honeybadger backs off before sending more. If the response has a `Retry-After` header, it waits that long.
* **401, 402, and 403** (for example, a bad API key): Honeybadger logs a warning and discards new reports for an hour. Errors and events pause separately.
* **Redirects** are never followed, so your API key is never sent to another host.

## Version requirements

Honeybadger for Rust requires **Rust 1.88 or newer**.

---

## Try Honeybadger for FREE

Intelligent logging, error tracking, and Just Enough APM™ in one dev-friendly platform. Find and fix problems before users notice.

[Start free trial](https://app.honeybadger.io/users/sign_up)

[See plans and pricing](https://www.honeybadger.io/plans/)
