go reference: Documentation for the Honeybadger Go client library (SDK) and platform.
# Honeybadger for Go
> Honeybadger monitors your Go applications for errors and exceptions so that you can fix them wicked fast.
[](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go) Hi there! You’ve found Honeybadger’s guide to **Go error tracking**. Once installed, Honeybadger will automatically report errors from your Go application. ## How you should read the docs [Section titled “How you should read the docs”](#how-you-should-read-the-docs) * If you’re installing Honeybadger in an application that uses Go’s **net/http** package, check out the **[HTTP integration guide](/lib/go/integrations/http/)**. * For all other Go applications, start with the **[General integration guide](/lib/go/integrations/other/)**. * The **How-to guides** (in the left-hand navigation menu) are general guides on how to do things with the library, and should apply to all types of applications. * There is additional reference material in the **Package reference** section. ## Sample application [Section titled “Sample application”](#sample-application) If you’d like to see the library in action before you integrate it with your apps, check out our [sample application](https://github.com/honeybadger-io/crywolf-go). You can deploy the sample app to your Heroku account by clicking this button: [](https://heroku.com/deploy?template=https://github.com/honeybadger-io/crywolf-go) Don’t forget to destroy the Heroku app after you’re done so that you aren’t charged for usage. ## Getting support [Section titled “Getting support”](#getting-support) If you’re having trouble working with the package (such as you aren’t receiving error reports when you should be): 1. Upgrade to the latest package version if possible (you can find a list of changes in the [CHANGELOG](https://github.com/honeybadger-io/honeybadger-go/blob/master/CHANGELOG.md)) 2. If you believe you’ve found a bug, [submit an issue on GitHub](https://github.com/honeybadger-io/honeybadger-go/issues/) For all other problems, contact support for help:
# Adding context to errors
> Add context to Go error reports with custom metadata to improve debugging and error resolution.
Honeybadger can display additional custom key/value metadata — or “context” — with each error report. Context is what you’re looking for if: * You want to record the current user’s id or email address at the time of an error * You need to send additional debugging information with an error * You have any other metadata you’d like to send with an error There are two ways to add context to errors in your code: [global](#global-context) and [local](#local-context). ## Global context [Section titled “Global context”](#global-context) Use [`honeybadger.SetContext`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#SetContext) to set context data that will be sent with any error that occurs:
```go
honeybadger.SetContext(honeybadger.Context{
"user_id": 1,
})
```
For example, it’s often useful to record the current user’s ID when an error occurs in a web app. To do that, use `SetContext` to set the user id on each request. If an error occurs, the id will be reported with it. **Note:** This method is currently shared across goroutines, and therefore may not be optimal for use in highly concurrent use cases, such as HTTP requests. See [issue #35](https://github.com/honeybadger-io/honeybadger-go/issues/35). ### Clearing global context [Section titled “Clearing global context”](#clearing-global-context) To clear all context data that was previously set with `SetContext`:
```go
honeybadger.ClearContext()
```
## Local context [Section titled “Local context”](#local-context) You can also add context to a single error report using [`Context`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Context) as an optional argument to `honeybadger.Notify`:
```go
honeybadger.Notify(err, honeybadger.Context{"user_id": 2})
```
Local context is useful when you want to add context that’s specific to a particular error, without affecting global context. ## Special context keys [Section titled “Special context keys”](#special-context-keys) While you can add any key/value data to context, a few keys have special meaning in Honeybadger: | Key | Description | | ------------ | ----------------------------------------------------------------------------------------------------- | | `user_id` | The `String` user ID used by Honeybadger to aggregate user data across occurrences on the error page. | | `user_email` | Same as `user_id`, but for email addresses | ## Limits [Section titled “Limits”](#limits) Honeybadger uses the following limits to ensure the service operates smoothly for everyone: * Nested objects have a max depth of 20 * Context values have a max size of 64Kb When an error notification includes context data that exceed these limits, the context data will be truncated, and the notification will still be processed.
# Customizing error grouping
> Customize how Honeybadger groups Go errors using error classes and fingerprints.
Honeybadger uses the error’s class name to group similar errors together. This works well for most cases, but you may want to customize grouping when: * Your error classes are generic (such as `errors.errorString`) * You want to group related errors together regardless of their class * You want to separate errors that have the same class but different causes ## Overriding the error class [Section titled “Overriding the error class”](#overriding-the-error-class) If your error classes are often generic, you can improve grouping by overriding the default class name with something more specific using [`ErrorClass`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#ErrorClass):
```go
honeybadger.Notify(err, honeybadger.ErrorClass{"DatabaseConnectionError"})
```
All errors with the same error class will be grouped together. ## Using custom fingerprints [Section titled “Using custom fingerprints”](#using-custom-fingerprints) To override grouping entirely, you can send a custom [`Fingerprint`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Fingerprint). All errors with the same fingerprint will be grouped together, regardless of error class:
```go
honeybadger.Notify(err, honeybadger.Fingerprint{"checkout-payment-failed"})
```
Fingerprints are useful when you want complete control over how errors are grouped. For example, you might want to group all payment-related errors together regardless of the underlying error type. ## Combining with other options [Section titled “Combining with other options”](#combining-with-other-options) You can combine error class or fingerprint with other notification options:
```go
honeybadger.Notify(err,
honeybadger.ErrorClass{"PaymentError"},
honeybadger.Context{"order_id": 12345},
honeybadger.Tags{"payment", "checkout"},
)
```
## Advanced: Using BeforeNotify for dynamic grouping [Section titled “Advanced: Using BeforeNotify for dynamic grouping”](#advanced-using-beforenotify-for-dynamic-grouping) For more complex grouping logic, you can use `BeforeNotify` to dynamically set the fingerprint based on the error. One common use case is grouping `errors.errorString` errors by their message instead of class:
```go
honeybadger.BeforeNotify(
func(notice *honeybadger.Notice) error {
if notice.ErrorClass == "errors.errorString" {
notice.Fingerprint = notice.Message
}
return nil
}
)
```
Note that in this example, the backtrace is ignored. If you want to group by message *and* backtrace, you could append data from `notice.Backtrace` to the fingerprint string. An alternate approach would be to override `notice.ErrorClass` with a more specific class name that may be inferred from the message.
# Reducing noise
> Filter and modify Go error notifications before they are sent to Honeybadger using BeforeNotify callbacks.
Sometimes you may want to modify the data sent to Honeybadger right before an error notification is sent, or skip the notification entirely. The `honeybadger.BeforeNotify` function lets you add callbacks to do this. ## Skipping notifications [Section titled “Skipping notifications”](#skipping-notifications) To skip certain errors from being reported, return an error from your `BeforeNotify` callback:
```go
honeybadger.BeforeNotify(
func(notice *honeybadger.Notice) error {
if notice.ErrorClass == "SkippedError" {
return fmt.Errorf("Skipping this notification")
}
// Return nil to send notification for all other classes.
return nil
}
)
```
When your callback returns an error, the notification is not sent to Honeybadger. ## Modifying notifications [Section titled “Modifying notifications”](#modifying-notifications) You can also modify the notice before it’s sent. For example, to change the error class for all errors:
```go
honeybadger.BeforeNotify(
func(notice *honeybadger.Notice) error {
// Errors in Honeybadger will always have the class name "GenericError".
notice.ErrorClass = "GenericError"
return nil
}
)
```
## Multiple callbacks [Section titled “Multiple callbacks”](#multiple-callbacks) You can register multiple `BeforeNotify` callbacks. They will be executed in the order they were registered. If any callback returns an error, the notification is skipped. ## Notice fields [Section titled “Notice fields”](#notice-fields) The [`Notice`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Notice) struct passed to your callback contains these fields you can inspect or modify: | Field | Type | Description | | ------------ | ---------- | -------------------- | | ErrorClass | string | Error type name | | ErrorMessage | string | Error message | | Fingerprint | string | Grouping fingerprint | | Tags | \[]string | Error tags | | URL | string | Request URL | | Context | Context | Custom context data | | Params | Params | URL/form parameters | | CGIData | CGIData | HTTP headers | | Backtrace | \[]\*Frame | Stack trace | | Env | string | Environment name | | Hostname | string | Server hostname | See the [Go package documentation](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go) for complete type definitions. ## Disabling notifications entirely [Section titled “Disabling notifications entirely”](#disabling-notifications-entirely) For development and testing, you may want to disable all error reporting. Use `NewNullBackend` to create a backend which swallows all errors:
```go
honeybadger.Configure(honeybadger.Configuration{Backend: honeybadger.NewNullBackend()})
```
This is useful to prevent sending unnecessary errors during development or in test environments.
# Reporting errors
> Manually report errors from Go applications to Honeybadger using the Notify function.
Honeybadger reports unhandled panics automatically when you use `honeybadger.Handler` or `honeybadger.Monitor()`. In all other cases, use `honeybadger.Notify` to send errors to Honeybadger. ## Using honeybadger.Notify [Section titled “Using honeybadger.Notify”](#using-honeybadgernotify) If you’ve handled a panic in your code, but would still like to report the error to Honeybadger, use `honeybadger.Notify`:
```go
if err != nil {
honeybadger.Notify(err)
}
```
## Adding context to notifications [Section titled “Adding context to notifications”](#adding-context-to-notifications) You can add local context using an optional second argument with [`Context`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Context):
```go
honeybadger.Notify(err, honeybadger.Context{"user_id": 2})
```
See [Adding context to errors](/lib/go/errors/context/) for more details. ## Customizing error grouping [Section titled “Customizing error grouping”](#customizing-error-grouping) Honeybadger uses the error’s class name to group similar errors together. If your error classes are often generic (such as `errors.errorString`), you can improve grouping by overriding the default with [`ErrorClass`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#ErrorClass):
```go
honeybadger.Notify(err, honeybadger.ErrorClass{"CustomClassName"})
```
To override grouping entirely, you can send a custom [`Fingerprint`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Fingerprint). All errors with the same fingerprint will be grouped together:
```go
honeybadger.Notify(err, honeybadger.Fingerprint{"A unique string"})
```
See [Customizing error grouping](/lib/go/errors/customizing-error-grouping/) for more details. ## Adding tags [Section titled “Adding tags”](#adding-tags) To tag errors in Honeybadger using [`Tags`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Tags):
```go
honeybadger.Notify(err, honeybadger.Tags{"timeout", "http"})
```
See [Tagging errors](/lib/go/errors/tagging-errors/) for more details. ## Combining options [Section titled “Combining options”](#combining-options) You can combine multiple options in a single `Notify` call:
```go
honeybadger.Notify(err,
honeybadger.Context{"user_id": 2},
honeybadger.Tags{"timeout", "http"},
honeybadger.ErrorClass{"TimeoutError"},
)
```
## Including HTTP request data [Section titled “Including HTTP request data”](#including-http-request-data) When reporting errors from HTTP handlers, you can pass the request directly to include URL, parameters, and headers automatically:
```go
honeybadger.Notify(err, r) // r is *http.Request
```
For more control, you can pass specific request data using [`Params`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Params) and [`CGIData`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#CGIData):
```go
// Include URL parameters
honeybadger.Notify(err, honeybadger.Params(r.URL.Query()))
// Include form data
r.ParseForm()
honeybadger.Notify(err, honeybadger.Params(r.Form))
// Include HTTP headers as CGI data
honeybadger.Notify(err, honeybadger.CGIData{
"REQUEST_METHOD": r.Method,
"HTTP_USER_AGENT": r.UserAgent(),
"REMOTE_ADDR": r.RemoteAddr,
})
// Include the request URL
honeybadger.Notify(err, r.URL)
```
**Note:** When using `honeybadger.Handler`, request data is captured automatically. See the [HTTP integration guide](/lib/go/integrations/http/) for details.
# Tagging errors
> Add tags to Go error reports in Honeybadger to organize and filter errors.
Tags allow you to categorize and filter errors in Honeybadger. You can use tags to: * Group errors by feature area (e.g., “checkout”, “auth”, “api”) * Mark errors by severity or priority * Filter errors in the Honeybadger dashboard ## Adding tags to errors [Section titled “Adding tags to errors”](#adding-tags-to-errors) To tag errors when reporting them to Honeybadger, use `honeybadger.Tags`:
```go
honeybadger.Notify(err, honeybadger.Tags{"timeout", "http"})
```
You can add multiple tags as separate strings in the slice. ## Combining tags with other options [Section titled “Combining tags with other options”](#combining-tags-with-other-options) Tags can be combined with context and other notification options:
```go
honeybadger.Notify(err,
honeybadger.Tags{"checkout", "payment"},
honeybadger.Context{"order_id": 12345},
)
```
See the [Go package documentation](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go) for more details.
# Insights overview
> Stream Go application logs and custom events into Honeybadger Insights, then query everything with BadgerQL.
[Insights](/guides/insights/) lets you observe what your Go application does in production. The Honeybadger Go package ships handlers for the standard `slog` package and for `zerolog`. Wire one in and every log line becomes a structured event in Insights, fields and all. From there, you can attach per-request fields to a derived logger, send custom events for moments that don’t fit a log shape, and use [BadgerQL](/guides/insights/badgerql/) to ask questions across the whole event stream. Any field you send is queryable as soon as it arrives, with no schema to define ahead of time. ## Wire up structured logging [Section titled “Wire up structured logging”](#wire-up-structured-logging) Construct an `slog` logger backed by the Honeybadger handler. The handler accepts a custom event type, which is the BadgerQL `event_type` field you will filter on later: Build an Insights logger
```go
import (
"log/slog"
"github.com/honeybadger-io/honeybadger-go"
hbslog "github.com/honeybadger-io/honeybadger-go/slog"
)
hbClient := honeybadger.New(honeybadger.Configuration{APIKey: "..."})
insightsLogger := slog.New(
hbslog.New(hbClient).WithEventType("http_request"),
).With("service", "checkouts", "commit", commit)
```
`service` and `commit` ride on every event from this logger, so you can filter by service across a fleet or split metrics by release. Keep this logger separate from your application’s main `slog` logger. Stdout and Insights serve different purposes, and routing every log line through Honeybadger inflates your event volume with noise. Stash the request-scoped derivative on context (below) so handlers emit through it deliberately. [Capturing logs](/lib/go/insights/capturing-logs/)slog and zerolog setup options. [Sending custom events](/lib/go/insights/sending-events/)The full honeybadger.Event API. ## Add per-request context [Section titled “Add per-request context”](#add-per-request-context) `slog`’s `.With()` returns a new logger with extra attributes attached to every subsequent log call. Use that to derive a request-scoped logger inside HTTP middleware. Attach only attributes that make sense for *every* request here, typically the request ID: Per-request logger in middleware
```go
func InsightsMiddleware(insightsLogger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
wrapped := &responseWriter{ResponseWriter: w, status: 200}
requestLogger := insightsLogger.With(
"request_id", r.Header.Get("X-Request-Id"),
)
r = r.WithContext(context.WithValue(r.Context(), loggerKey, requestLogger))
next.ServeHTTP(wrapped, r)
requestLogger.LogAttrs(r.Context(), slog.LevelInfo, "request",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", wrapped.status),
slog.Int64("duration", time.Since(start).Microseconds()),
)
})
}
}
```
Every request now produces one `http_request` event with `method`, `path`, `status`, `duration` (microseconds), and `request_id`. Slowest endpoints by p95: Slowest endpoints
```badgerql
filter event_type::str == "http_request"
| stats percentile(95, duration::float) as p95_us by path::str
| sort p95_us desc
| limit 5
| only path, toHumanString(p95_us, "microseconds") as p95
```
| path | p95 | | -------------------- | ----- | | /checkouts/authorize | 412ms | | /reports/generate | 287ms | | /search | 138ms | | /accounts/upgrade | 96ms | | /users/me | 41ms | ## Record application events [Section titled “Record application events”](#record-application-events) For application events recorded from inside a handler (a payment authorized, a subscription upgrading, a feature toggle flipping), emit them through a further-derived logger pulled from context. Handler-specific attributes attached via `.With()` ride along with `request_id` and anything else the middleware put on the request logger: Send a custom payment event
```go
func authorizeCheckout(w http.ResponseWriter, r *http.Request) {
logger := r.Context().Value(loggerKey).(*slog.Logger).
With("checkout_variant", r.URL.Query().Get("variant"))
// ...
logger.LogAttrs(r.Context(), slog.LevelInfo, "payment authorized",
slog.String("event_type", "payment.authorized"),
slog.String("payment_provider", payment.Provider),
slog.Float64("amount", checkout.Total),
slog.String("currency", checkout.Currency),
slog.String("authorization_id", payment.AuthorizationID),
)
}
```
This query breaks down the amounts collected by variant and provider: Payments by variant and provider
```badgerql
filter event_type::str == "payment.authorized"
| stats
count() as authorizations,
sum(amount::float) as authorized_amount
by checkout_variant::str, payment_provider::str
| sort authorized_amount desc
```
| authorizations | authorized\_amount | checkout\_variant | payment\_provider | | -------------- | ------------------ | ----------------- | ----------------- | | 413 | 34108.00 | new | stripe | | 218 | 18722.00 | new | paypal | | 418 | 32167.00 | control | stripe | | 220 | 13639.00 | control | paypal |
# Capturing logs
> Send structured logs from Go applications to Honeybadger Insights using slog or zerolog.
Honeybadger provides handlers for popular Go logging libraries that send structured logs directly to Honeybadger Insights as events. ## Supported libraries [Section titled “Supported libraries”](#supported-libraries) * [slog](#slog) - Go’s standard structured logging package (Go 1.21+) * [zerolog](#zerolog) - High-performance JSON logger *** ## slog [Section titled “slog”](#slog) The slog handler sends logs from Go’s standard `log/slog` package to Honeybadger Insights. **Requires Go 1.21+** ### Quick start [Section titled “Quick start”](#quick-start)
```go
import (
"log/slog"
"github.com/honeybadger-io/honeybadger-go"
hbslog "github.com/honeybadger-io/honeybadger-go/slog"
)
func main() {
client := honeybadger.New(honeybadger.Configuration{
APIKey: "PROJECT_API_KEY",
})
logger := slog.New(hbslog.New(client))
logger.Info("app started", "version", "1.0.0")
}
```
This produces an event in Honeybadger Insights:
```json
{
"event_type": "log",
"level": "INFO",
"message": "app started",
"version": "1.0.0"
}
```
### Event types [Section titled “Event types”](#event-types) The default event type is `log`. Set a custom event type for all logs using `WithEventType`:
```go
audit := slog.New(hbslog.New(client).WithEventType("audit"))
audit.Info("user logged in", "user_id", 42)
```
Set the event type per log call with the `event_type` attribute:
```go
logger.Info("user signup", "event_type", "user_lifecycle", "user_id", 123)
logger.Info("payment processed", "event_type", "payment", "amount", 99.99)
```
### Attributes and groups [Section titled “Attributes and groups”](#attributes-and-groups) Use `WithAttrs` to add attributes to all logs, and `WithGroup` to nest attributes:
```go
handler := hbslog.New(client).
WithAttrs([]slog.Attr{slog.String("service", "api")}).
WithGroup("http")
logger := slog.New(handler)
logger.Info("request handled", "status", 200, "method", "POST")
```
This produces:
```json
{
"event_type": "log",
"level": "INFO",
"message": "request handled",
"service": "api",
"http": {
"status": 200,
"method": "POST"
}
}
```
### Log level filtering [Section titled “Log level filtering”](#log-level-filtering) Control which logs are sent to Honeybadger:
```go
// Only send WARN and above
handler := hbslog.New(client).WithLevel(slog.LevelWarn)
logger := slog.New(handler)
logger.Info("This is ignored")
logger.Warn("This is sent")
```
Use `slog.LevelVar` for dynamic level changes at runtime:
```go
levelVar := new(slog.LevelVar)
levelVar.Set(slog.LevelInfo)
handler := hbslog.New(client).WithLevel(levelVar)
logger := slog.New(handler)
levelVar.Set(slog.LevelDebug) // Now debug logs will be sent
```
*** ## zerolog [Section titled “zerolog”](#zerolog) The zerolog adapter sends logs from the `rs/zerolog` package to Honeybadger Insights. ### Quick start [Section titled “Quick start”](#quick-start-1)
```go
import (
"github.com/rs/zerolog"
"github.com/honeybadger-io/honeybadger-go"
hbzerolog "github.com/honeybadger-io/honeybadger-go/zerolog"
)
func main() {
client := honeybadger.New(honeybadger.Configuration{
APIKey: "PROJECT_API_KEY",
})
writer := hbzerolog.New(client)
logger := zerolog.New(writer).With().Timestamp().Logger()
logger.Info().Msg("hello")
}
```
### Options [Section titled “Options”](#options) #### WithEventType [Section titled “WithEventType”](#witheventtype) Sets the default event type for all logs (default: `"log"`). Override per-log by including an `event_type` field:
```go
writer := hbzerolog.New(client, hbzerolog.WithEventType("app_log"))
```
#### WithKeys [Section titled “WithKeys”](#withkeys) Customize field names if your zerolog uses non-standard keys. The writer remaps the time field to `ts` for Honeybadger:
```go
writer := hbzerolog.New(
client,
hbzerolog.WithEventType("app_log"),
hbzerolog.WithKeys("timestamp", "severity"), // defaults: "time", "level"
)
```
# Event context
> Add contextual data to Insights events in Go to improve debugging and understanding of application behavior.
You can add custom metadata to the events sent to Honeybadger Insights by using the `SetEventContext` function. This metadata will be merged into all events sent via `honeybadger.Event()`. ## Setting event context [Section titled “Setting event context”](#setting-event-context) Use `honeybadger.SetEventContext()` to set context data that will be included with all events:
```go
honeybadger.SetEventContext(honeybadger.Context{
"user_id": 123,
"account": "acme",
})
```
Event data passed directly to `Event()` takes precedence over event context if there are conflicting keys. ## Clearing event context [Section titled “Clearing event context”](#clearing-event-context) To clear all event context data that was previously set:
```go
honeybadger.ClearEventContext()
```
## Example usage [Section titled “Example usage”](#example-usage) A common pattern is to set event context early in a request lifecycle:
```go
func handleRequest(w http.ResponseWriter, r *http.Request) {
user := getCurrentUser(r)
honeybadger.SetEventContext(honeybadger.Context{
"user_id": user.ID,
"account_id": user.AccountID,
})
// All events sent during this request will include user context
honeybadger.Event("page_view", map[string]any{
"path": r.URL.Path,
})
}
```
**Note:** Event context is stored globally and shared across goroutines. For highly concurrent applications, consider passing context data directly to `Event()` instead.
# Filtering events
> Filter Insights events in Go applications to reduce noise and focus on relevant data.
You can filter out or customize events sent to Honeybadger Insights by using the `honeybadger.BeforeEvent()` function. This allows you to modify event data or skip events entirely before they are sent. ## Modifying events [Section titled “Modifying events”](#modifying-events) To modify or augment event data before it’s sent, add a callback that modifies the event map and returns `nil`:
```go
honeybadger.BeforeEvent(
func(event map[string]any) error {
event["environment"] = "production"
return nil
}
)
```
## Dropping events [Section titled “Dropping events”](#dropping-events) To skip events from being sent, return `honeybadger.ErrEventDropped`:
```go
honeybadger.BeforeEvent(
func(event map[string]any) error {
if event["event_type"] == "debug_event" {
return honeybadger.ErrEventDropped
}
return nil
}
)
```
## Multiple callbacks [Section titled “Multiple callbacks”](#multiple-callbacks) You can register multiple `BeforeEvent` callbacks. They will be executed in the order they were registered. If any callback returns `ErrEventDropped`, the event is skipped. ## Example: Filtering sensitive data [Section titled “Example: Filtering sensitive data”](#example-filtering-sensitive-data) A common use case is to filter sensitive data from events:
```go
honeybadger.BeforeEvent(
func(event map[string]any) error {
// Remove sensitive fields
delete(event, "password")
delete(event, "credit_card")
// Anonymize email addresses
if email, ok := event["email"].(string); ok {
event["email"] = anonymizeEmail(email)
}
return nil
}
)
```
## Example: Dropping high-volume events [Section titled “Example: Dropping high-volume events”](#example-dropping-high-volume-events) You might want to drop certain high-volume events to reduce costs:
```go
honeybadger.BeforeEvent(
func(event map[string]any) error {
// Drop health check events
if event["event_type"] == "health_check" {
return honeybadger.ErrEventDropped
}
// Drop events from internal services
if source, ok := event["source"].(string); ok {
if source == "internal-monitoring" {
return honeybadger.ErrEventDropped
}
}
return nil
}
)
```
# Sending custom events
> Send custom events to Honeybadger Insights for tracking application behavior and metrics in Go.
Honeybadger’s Go package can be used to send events to [Honeybadger Insights](/guides/insights/). ## Sending custom events [Section titled “Sending custom events”](#sending-custom-events) Use `honeybadger.Event()` to send custom events:
```go
honeybadger.Event("user_login", map[string]any{
"user_id": 123,
"email": "user@example.com",
})
```
The first argument is the event type, and the second is a map of event data. Events are batched and sent asynchronously for optimal performance. ## Configuration [Section titled “Configuration”](#configuration) You can configure batching, retries, and throttling behavior. See [Configuration](/lib/go/reference/configuration/) for details on the following options: | Option | Default | Description | | ----------------------- | ---------- | ----------------------------------- | | `EventsBatchSize` | 1000 | Maximum events per batch | | `EventsTimeout` | 30 seconds | Request timeout | | `EventsMaxQueueSize` | 100000 | Maximum events to queue | | `EventsMaxRetries` | 3 | Maximum retry attempts | | `EventsThrottleWait` | 60 seconds | Wait time before retrying | | `EventsDropLogInterval` | 60 seconds | Interval for logging dropped events |
# HTTP integration guide
> Install and configure Honeybadger for Go applications using net/http with automatic panic reporting.
**Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **Go error tracking** for applications using the `net/http` package. Once installed, Honeybadger will automatically report panics from your HTTP handlers. ## Installing the package [Section titled “Installing the package”](#installing-the-package) To install, grab the package from GitHub:
```sh
go get github.com/honeybadger-io/honeybadger-go
```
Then add an import to your application code:
```go
import "github.com/honeybadger-io/honeybadger-go"
```
## Configuring your API key [Section titled “Configuring your API key”](#configuring-your-api-key) Configure your API key using `honeybadger.Configure`:
```go
honeybadger.Configure(honeybadger.Configuration{APIKey: "PROJECT_API_KEY"})
```
You can also configure Honeybadger via the `HONEYBADGER_API_KEY` environment variable. See [Configuration](/lib/go/reference/configuration/) for more options. ## Enabling automatic panic reporting [Section titled “Enabling automatic panic reporting”](#enabling-automatic-panic-reporting) To automatically report panics which happen during an HTTP request, wrap your `http.Handler` function with [`honeybadger.Handler`](https://pkg.go.dev/github.com/honeybadger-io/honeybadger-go#Handler):
```go
log.Fatal(http.ListenAndServe(":8080", honeybadger.Handler(handler)))
```
Request data such as cookies and params will automatically be reported with errors which happen inside `honeybadger.Handler`. Make sure you recover from panics after Honeybadger’s Handler has been executed to ensure all panics are reported. ## What data is captured [Section titled “What data is captured”](#what-data-is-captured) When a panic occurs inside `honeybadger.Handler`, the following request data is automatically included in the error report: * Request URL and method * URL query parameters * Form data (if parsed) * HTTP headers (as CGI variables) * Cookies For manually reported errors, pass the request to include this data:
```go
func myHandler(w http.ResponseWriter, r *http.Request) {
if err := doSomething(); err != nil {
honeybadger.Notify(err, r)
}
}
```
See [Reporting errors](/lib/go/errors/reporting-errors/) for more options. ## Testing your installation [Section titled “Testing your installation”](#testing-your-installation) To verify that your installation is working, you can trigger a test panic in one of your HTTP handlers:
```go
func testHandler(w http.ResponseWriter, r *http.Request) {
panic("Testing Honeybadger!")
}
```
Visit the route that triggers this handler, then check your Honeybadger dashboard for the error. ## Next steps [Section titled “Next steps”](#next-steps) * Learn how to [report errors manually](/lib/go/errors/reporting-errors/) * Add [context to your errors](/lib/go/errors/context/) * Explore [configuration options](/lib/go/reference/configuration/)
# Other Go applications
> Install and configure Honeybadger for Go applications with automatic panic monitoring and manual error reporting.
**Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **Go error tracking** for standalone applications, CLI tools, workers, and other non-HTTP Go programs. Once installed, Honeybadger will report panics and errors from your application. ## Installing the package [Section titled “Installing the package”](#installing-the-package) To install, grab the package from GitHub:
```sh
go get github.com/honeybadger-io/honeybadger-go
```
Then add an import to your application code:
```go
import "github.com/honeybadger-io/honeybadger-go"
```
## Configuring your API key [Section titled “Configuring your API key”](#configuring-your-api-key) Configure your API key using `honeybadger.Configure`:
```go
honeybadger.Configure(honeybadger.Configuration{APIKey: "PROJECT_API_KEY"})
```
You can also configure Honeybadger via the `HONEYBADGER_API_KEY` environment variable. See [Configuration](/lib/go/reference/configuration/) for more options. ## Enabling automatic panic reporting [Section titled “Enabling automatic panic reporting”](#enabling-automatic-panic-reporting) To report all unhandled panics which happen in your application, add the following to `main()`:
```go
func main() {
defer honeybadger.Monitor()
// application code...
}
```
**Important:** `honeybadger.Monitor()` will re-panic after it reports the error, so make sure that it is only called once before recovering from the panic (or allowing the process to crash). You can also monitor specific functions:
```go
func risky() {
defer honeybadger.Monitor()
// risky business logic...
}
```
## Manually reporting errors [Section titled “Manually reporting errors”](#manually-reporting-errors) To report an error manually, use `honeybadger.Notify`:
```go
if err != nil {
honeybadger.Notify(err)
}
```
See [Reporting errors](/lib/go/errors/reporting-errors/) for more details. ## Testing your installation [Section titled “Testing your installation”](#testing-your-installation) To verify that your installation is working, you can add a test panic:
```go
func main() {
defer honeybadger.Monitor()
panic("Testing Honeybadger!")
}
```
Run your application, then check your Honeybadger dashboard for the error. ## Next steps [Section titled “Next steps”](#next-steps) * Learn how to [report errors manually](/lib/go/errors/reporting-errors/) * Add [context to your errors](/lib/go/errors/context/) * Explore [configuration options](/lib/go/reference/configuration/)
# Configuration
> Complete configuration reference for Honeybadger's Go library with all available options and settings.
You can configure Honeybadger using the `honeybadger.Configure` method:
```go
honeybadger.Configure(honeybadger.Configuration{
APIKey: "PROJECT_API_KEY",
Env: "production",
})
```
You can also configure most options via environment variables. ## Configuration options [Section titled “Configuration options”](#configuration-options) | Name | Type | Default | Example | Environment variable | | --------------------- | --------------------- | ------------------------------ | ------------------------------------ | ---------------------------------------------------- | | APIKey | `string` | `""` | `"badger01"` | `HONEYBADGER_API_KEY` | | Root | `string` | The current working directory | `"/path/to/project"` | `HONEYBADGER_ROOT` | | Env | `string` | `""` | `"production"` | `HONEYBADGER_ENV` | | Hostname | `string` | The hostname of current server | `"badger01"` | `HONEYBADGER_HOSTNAME` | | Endpoint | `string` | `"https://api.honeybadger.io"` | `"https://honeybadger.example.com/"` | `HONEYBADGER_ENDPOINT` | | Sync | `bool` | `false` | `true` | `HONEYBADGER_SYNC` | | Timeout | `time.Duration` | 3 seconds | `10 * time.Second` | `HONEYBADGER_TIMEOUT` (nanoseconds) | | Logger | `honeybadger.Logger` | Logs to stderr | `CustomLogger{}` | n/a | | Backend | `honeybadger.Backend` | HTTP backend | `CustomBackend{}` | n/a | | EventsBatchSize | `int` | 1000 | `500` | `HONEYBADGER_EVENTS_BATCH_SIZE` | | EventsTimeout | `time.Duration` | 30 seconds | `10 * time.Second` | `HONEYBADGER_EVENTS_TIMEOUT` (nanoseconds) | | EventsMaxQueueSize | `int` | 100000 | `50000` | `HONEYBADGER_EVENTS_MAX_QUEUE_SIZE` | | EventsMaxRetries | `int` | 3 | `5` | `HONEYBADGER_EVENTS_MAX_RETRIES` | | EventsThrottleWait | `time.Duration` | 60 seconds | `30 * time.Second` | `HONEYBADGER_EVENTS_THROTTLE_WAIT` (nanoseconds) | | EventsDropLogInterval | `time.Duration` | 60 seconds | `30 * time.Second` | `HONEYBADGER_EVENTS_DROP_LOG_INTERVAL` (nanoseconds) | ## Configuration via environment variables [Section titled “Configuration via environment variables”](#configuration-via-environment-variables) The following environment variables are supported: * `HONEYBADGER_API_KEY` - Your Honeybadger API key * `HONEYBADGER_ENV` - The environment name (e.g., “production”, “staging”) * `HONEYBADGER_ROOT` - The project root directory * `HONEYBADGER_HOSTNAME` - The server hostname * `HONEYBADGER_ENDPOINT` - Custom API endpoint URL * `HONEYBADGER_SYNC` - Set to “true” for synchronous error reporting * `HONEYBADGER_TIMEOUT` - Request timeout in nanoseconds * `HONEYBADGER_EVENTS_BATCH_SIZE` - Maximum events per batch * `HONEYBADGER_EVENTS_TIMEOUT` - Events request timeout in nanoseconds * `HONEYBADGER_EVENTS_MAX_QUEUE_SIZE` - Maximum events to queue * `HONEYBADGER_EVENTS_MAX_RETRIES` - Maximum retry attempts for events * `HONEYBADGER_EVENTS_THROTTLE_WAIT` - Wait time before retrying in nanoseconds * `HONEYBADGER_EVENTS_DROP_LOG_INTERVAL` - Interval for logging dropped events in nanoseconds ## Sync mode [Section titled “Sync mode”](#sync-mode) By default, notices are sent via a separate worker goroutine. This is ideal for long-running applications as it keeps Honeybadger from blocking during execution. However, this can be a problem for short-running applications (lambdas, for example) as the program might terminate before all messages are processed. To combat this, you can configure Honeybadger to work in “Sync” mode which blocks until notices are sent when `honeybadger.Notify` is executed:
```go
honeybadger.Configure(honeybadger.Configuration{Sync: true})
```
Alternatively, if you want asynchronous behavior but need to ensure notices are sent before your program exits, you can call `honeybadger.Flush`:
```go
honeybadger.Notify("I errored.")
honeybadger.Flush()
```
## Custom logger [Section titled “Custom logger”](#custom-logger) You can provide a custom logger by implementing the `honeybadger.Logger` interface:
```go
honeybadger.Configure(honeybadger.Configuration{
Logger: myCustomLogger,
})
```
## Custom backend [Section titled “Custom backend”](#custom-backend) For testing or custom integrations, you can provide a custom backend:
```go
honeybadger.Configure(honeybadger.Configuration{
Backend: myCustomBackend,
})
```
To disable error reporting entirely (useful for development), use the null backend:
```go
honeybadger.Configure(honeybadger.Configuration{
Backend: honeybadger.NewNullBackend(),
})
```
## Creating a new client [Section titled “Creating a new client”](#creating-a-new-client) In the same way that the log library provides a predefined “standard” logger, honeybadger defines a standard client which may be accessed directly via `honeybadger`. A new client may also be created by calling `honeybadger.New`:
```go
hb := honeybadger.New(honeybadger.Configuration{APIKey: "some other api key"})
hb.Notify("This error was reported by an alternate client.")
```
# Supported versions
> Go versions supported by the Honeybadger Go library.
This library supports the last two major Go releases, consistent with the Go team’s [release policy](https://go.dev/doc/devel/release): * Go 1.25.x * Go 1.24.x Older versions may work but are not officially supported or tested.