Skip to content

Honeybadger for Rust

View Markdown

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.

Source code • API docs • Examples

Add honeybadger to your Cargo.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.

Initialize Honeybadger near the top of main. Configure your API key, or set it in the HONEYBADGER_API_KEY environment variable:

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 ...
}

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.

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.

Any error that implements std::error::Error 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:

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).

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

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.

Honeybadger can attach key/value context to your error reports. You can add it to a single error (local context), to every error (global context), or to every error in a request (per-request context).

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

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.

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

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

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:

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.

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:

[dependencies]
honeybadger = { version = "0.5", features = ["tokio"] }
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):

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.

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

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:

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.

Add tags to categorize an error:

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

Honeybadger groups occurrences of the same error together. To control the grouping, set an explicit fingerprint:

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.

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:

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.

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

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:

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:

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()

You can also send structured events to Honeybadger Insights:

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:

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

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

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, 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.

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

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()
NameTypeDefaultEnvironment var
events_enabledbooltrueHONEYBADGER_EVENTS_ENABLED
events_batch_sizeusize1000HONEYBADGER_EVENTS_BATCH_SIZE
events_flush_intervalDuration30 secondsHONEYBADGER_EVENTS_FLUSH_INTERVAL
events_queue_sizeusize10000HONEYBADGER_EVENTS_QUEUE_SIZE
events_max_retriesu323HONEYBADGER_EVENTS_MAX_RETRIES
events_sample_rateu8100HONEYBADGER_EVENTS_SAMPLE_RATE
events_attach_hostnamebooltrueHONEYBADGER_EVENTS_ATTACH_HOSTNAME
events_attach_environmentbooltrueHONEYBADGER_EVENTS_ATTACH_ENVIRONMENT
before_eventhooknonen/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.

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):

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).

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.

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

The following options are available:

NameTypeDefaultEnvironment var
api_keyStringnoneHONEYBADGER_API_KEY
envStringnoneHONEYBADGER_ENV
exclude_envslist of strings["development", "test"]n/a
enabledboolderived from env and exclude_envsHONEYBADGER_ENABLED
endpointStringhttps://api.honeybadger.ioHONEYBADGER_ENDPOINT
rootStringthe current directoryHONEYBADGER_ROOT
hostnameStringthe system hostnameHONEYBADGER_HOSTNAME
revisionStringnoneHONEYBADGER_REVISION
filter_keyslist of strings["password", "credit_card", "secret"]n/a
ignore_classeslist of strings[]n/a
breadcrumbs_enabledbooltruen/a
install_panic_hookbooltruen/a
notice_queue_sizeusize100n/a
connect_timeoutDuration4 secondsn/a
request_timeoutDuration5 secondsn/a
before_notifyhooknonen/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.

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

Terminal window
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.

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

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.

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 crate. To see them, add a log backend such as env_logger, call env_logger::init() at the start of main, and turn on debug logging:

Terminal window
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.

Honeybadger for Rust requires Rust 1.88 or newer.