bugsnag

package module
v2.4.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2024 License: MIT Imports: 21 Imported by: 1,587

README

SmartBear BugSnag logo

Error monitoring and reporting for Go

Documentation Go Reference Build status

Automatically detect crashes and report errors in your Go apps. Get alerts about errors and panics in real-time, including detailed error reports with diagnostic information. Understand and resolve issues as fast as possible.

Learn more about BugSnag's Go error monitoring and error reporting solution.

Features

  • Automatically report unhandled errors and panics
  • Report handled errors
  • Attach user information to determine how many people are affected by a crash
  • Send customized diagnostic data

Getting Started

  1. Create a BugSnag account
  2. Complete the instructions in the integration guide for your framework:
  3. Relax!

Support

Contributing

All contributors are welcome! For information on how to build, test and release bugsnag-go, see our contributing guide.

License

The BugSnag error reporter for Go is free software released under the MIT License. See LICENSE.txt for details.

Documentation

Overview

Package bugsnag captures errors in real-time and reports them to BugSnag (http://bugsnag.com).

Using bugsnag-go is a three-step process.

1. As early as possible in your program configure the notifier with your APIKey. This sets up handling of panics that would otherwise crash your app.

func init() {
	bugsnag.Configure(bugsnag.Configuration{
		APIKey: "YOUR_API_KEY_HERE",
	})
}

2. Add bugsnag to places that already catch panics. For example you should add it to the HTTP server when you call ListenAndServer:

http.ListenAndServe(":8080", bugsnag.Handler(nil))

If that's not possible, you can also wrap each HTTP handler manually:

http.HandleFunc("/" bugsnag.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
	...
})

3. To notify BugSnag of an error that is not a panic, pass it to bugsnag.Notify. This will also log the error message using the configured Logger.

if err != nil {
	bugsnag.Notify(err)
}

For detailed integration instructions see https://docs.bugsnag.com/platforms/go.

Configuration

The only required configuration is the BugSnag API key which can be obtained by clicking "Project Settings" on the top of your BugSnag dashboard after signing up. We also recommend you set the ReleaseStage, AppType, and AppVersion if these make sense for your deployment workflow.

RawData

If you need to attach extra data to BugSnag events, you can do that using the rawData mechanism. Most of the functions that send errors to BugSnag allow you to pass in any number of interface{} values as rawData. The rawData can consist of the Severity, Context, User or MetaData types listed below, and there is also builtin support for *http.Requests.

bugsnag.Notify(err, bugsnag.SeverityError)

If you want to add custom tabs to your bugsnag dashboard you can pass any value in as rawData, and then process it into the event's metadata using a bugsnag.OnBeforeNotify() hook.

bugsnag.Notify(err, account)

bugsnag.OnBeforeNotify(func (e *bugsnag.Event, c *bugsnag.Configuration) {
	for datum := range e.RawData {
		if account, ok := datum.(Account); ok {
			e.MetaData.Add("account", "name", account.Name)
			e.MetaData.Add("account", "url", account.URL)
		}
	}
})

If necessary you can pass Configuration in as rawData, or modify the Configuration object passed into OnBeforeNotify hooks. Configuration passed in this way only affects the current notification.

Index

Examples

Constants

View Source
const (
	SeverityReasonCallbackSpecified        SeverityReason = "userCallbackSetSeverity"
	SeverityReasonHandledError                            = "handledError"
	SeverityReasonHandledPanic                            = "handledPanic"
	SeverityReasonUnhandledError                          = "unhandledError"
	SeverityReasonUnhandledMiddlewareError                = "unhandledErrorMiddleware"
	SeverityReasonUnhandledPanic                          = "unhandledPanic"
	SeverityReasonUserSpecified                           = "userSpecifiedSeverity"
)
View Source
const VERSION = "1.9.1"

VERSION defines the version of this Bugsnag notifier

Variables

View Source
var (
	SeverityError   = severity{"error"}
	SeverityWarning = severity{"warning"}
	SeverityInfo    = severity{"info"}
)

Sets the severity of the error on Bugsnag. These values can be passed to Notify, Recover or AutoNotify as rawData.

View Source
var DefaultSessionPublishInterval = 60 * time.Second

DefaultSessionPublishInterval defines how often sessions should be sent to Bugsnag. Deprecated: Exposed for developer sanity in testing. Modify at own risk.

Functions

func AttachRequestData added in v1.4.0

func AttachRequestData(ctx context.Context, r *http.Request) context.Context

AttachRequestData returns a child of the given context with the request object attached for later extraction by the notifier in order to automatically record request data

func AutoNotify

func AutoNotify(rawData ...interface{})

AutoNotify logs a panic on a goroutine and then repanics. It should only be used in places that have existing panic handlers further up the stack. Although it's not strictly enforced, it's highly recommended to pass a context.Context object that has at one-point been returned from bugsnag.StartSession. Doing so ensures your stability score remains accurate, and future versions of Bugsnag may extract more useful information from this context. The rawData is used to send extra information along with any panics that are handled this way. Usage:

 go func() {
     ctx := bugsnag.StartSession(context.Background())
		defer bugsnag.AutoNotify(ctx)
     // (possibly crashy code)
 }()

See also: bugsnag.Recover()

Example
bugsnag.Configure(bugsnag.Configuration{APIKey: exampleAPIKey})
createAccount := func(ctx context.Context) {
	fmt.Println("Creating account and passing context around...")
}
ctx := bugsnag.StartSession(context.Background())
defer bugsnag.AutoNotify(ctx)
createAccount(ctx)
Output:

Creating account and passing context around...

func Configure

func Configure(config Configuration)

Configure Bugsnag. The only required setting is the APIKey, which can be obtained by clicking on "Settings" in your Bugsnag dashboard. This function is also responsible for installing the global panic handler, so it should be called as early as possible in your initialization process.

Example
bugsnag.Configure(bugsnag.Configuration{
	APIKey:       "YOUR_API_KEY_HERE",
	ReleaseStage: "production",
	// See bugsnag.Configuration for other fields
})
Output:

func Handler

func Handler(h http.Handler, rawData ...interface{}) http.Handler

Handler creates an http Handler that notifies Bugsnag any panics that happen. It then repanics so that the default http Server panic handler can handle the panic too. The rawData is used to send extra information along with any panics that are handled this way.

Example
handleReq := func(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Handling HTTP request")
}

// Set up your http handlers as usual
http.HandleFunc("/", handleReq)

// use bugsnag.Handler(nil) to wrap the default http handlers
// so that Bugsnag is automatically notified about panics.
http.ListenAndServe(":1234", bugsnag.Handler(nil))
Output:

Example (CustomHandlers)
handleReq := func(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Handling GET")
}

// If you're using custom handlers, wrap the handlers explicitly.
handler := http.NewServeMux()
http.HandleFunc("/", handleReq)
// use bugsnag.Handler(handler) to wrap the handlers so that Bugsnag is
// automatically notified about panics
http.ListenAndServe(":1234", bugsnag.Handler(handler))
Output:

Example (CustomServer)
handleReq := func(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Handling GET")
}

// If you're using a custom server, set the handlers explicitly.
http.HandleFunc("/", handleReq)

srv := http.Server{
	Addr:        ":1234",
	ReadTimeout: 10 * time.Second,
	// use bugsnag.Handler(nil) to wrap the default http handlers
	// so that Bugsnag is automatically notified about panics.
	Handler: bugsnag.Handler(nil),
}
srv.ListenAndServe()
Output:

func HandlerFunc

func HandlerFunc(h http.HandlerFunc, rawData ...interface{}) http.HandlerFunc

HandlerFunc creates an http HandlerFunc that notifies Bugsnag about any panics that happen. It then repanics so that the default http Server panic handler can handle the panic too. The rawData is used to send extra information along with any panics that are handled this way. If you have already wrapped your http server using bugsnag.Handler() you don't also need to wrap each HandlerFunc.

func Notify

func Notify(err error, rawData ...interface{}) error

Notify sends an error.Error to Bugsnag along with the current stack trace. If at all possible, it is recommended to pass in a context.Context, e.g. from a http.Request or bugsnag.StartSession() as Bugsnag will be able to extract additional information in some cases. The rawData is used to send extra information along with the error. For example you can pass the current http.Request to Bugsnag to see information about it in the dashboard, or set the severity of the notification. For a detailed list of the information that can be extracted, see https://docs.bugsnag.com/platforms/go/reporting-handled-errors/

Example
ctx := context.Background()
ctx = bugsnag.StartSession(ctx)
_, err := net.Listen("tcp", ":80")

if err != nil {
	bugsnag.Notify(err, ctx)
}
Output:

Example (Details)
ctx := context.Background()
ctx = bugsnag.StartSession(ctx)
_, err := net.Listen("tcp", ":80")

if err != nil {
	bugsnag.Notify(err, ctx,
		// show as low-severity
		bugsnag.SeverityInfo,
		// set the context
		bugsnag.Context{String: "createlistener"},
		// pass the user id in to count users affected.
		bugsnag.User{Id: "123456789"},
		// custom meta-data tab
		bugsnag.MetaData{
			"Listen": {
				"Protocol": "tcp",
				"Port":     "80",
			},
		},
	)
}
Output:

func OnBeforeNotify

func OnBeforeNotify(callback func(event *Event, config *Configuration) error)

OnBeforeNotify adds a callback to be run before a notification is sent to Bugsnag. It can be used to modify the event or its MetaData. Changes made to the configuration are local to notifying about this event. To prevent the event from being sent to Bugsnag return an error, this error will be returned from bugsnag.Notify() and the event will not be sent.

Example
type Job struct {
	Retry     bool
	UserID    string
	UserEmail string
}

bugsnag.OnBeforeNotify(func(event *bugsnag.Event, config *bugsnag.Configuration) error {
	// Search all the RawData for any *Job pointers that we're passed in
	// to bugsnag.Notify() and friends.
	for _, datum := range event.RawData {
		if job, ok := datum.(*Job); ok {
			// don't notify bugsnag about errors in retries
			if job.Retry {
				return fmt.Errorf("bugsnag middleware: not notifying about job retry")
			}
			// add the job as a tab on Bugsnag.com
			event.MetaData.AddStruct("Job", job)
			// set the user correctly
			event.User = &bugsnag.User{Id: job.UserID, Email: job.UserEmail}
		}
	}

	// continue notifying as normal
	return nil
})
Output:

func Recover

func Recover(rawData ...interface{})

Recover logs a panic on a goroutine and then recovers. Although it's not strictly enforced, it's highly recommended to pass a context.Context object that has at one-point been returned from bugsnag.StartSession. Doing so ensures your stability score remains accurate, and future versions of Bugsnag may extract more useful information from this context. The rawData is used to send extra information along with any panics that are handled this way Usage:

go func() {
    ctx := bugsnag.StartSession(context.Background())
    defer bugsnag.Recover(ctx)
    // (possibly crashy code)
}()

If you wish that any panics caught by the call to Recover shall affect your stability score (it does not by default):

go func() {
    ctx := bugsnag.StartSession(context.Background())
    defer bugsnag.Recover(ctx, bugsnag.HandledState{Unhandled: true})
    // (possibly crashy code)
}()

See also: bugsnag.AutoNotify()

Example
bugsnag.Configure(bugsnag.Configuration{APIKey: exampleAPIKey})
panicFunc := func() {
	fmt.Println("About to panic")
	panic("Oh noes")
}

// Will recover when panicFunc panics
func() {
	ctx := bugsnag.StartSession(context.Background())
	defer bugsnag.Recover(ctx)
	panicFunc()
}()

fmt.Println("Panic recovered")
Output:

About to panic
Panic recovered

func StartSession added in v1.4.0

func StartSession(ctx context.Context) context.Context

StartSession creates new context from the context.Context instance with Bugsnag session data attached. Will start the session tracker if not already started

Types

type Configuration

type Configuration struct {
	// Your Bugsnag API key, e.g. "c9d60ae4c7e70c4b6c4ebd3e8056d2b8". You can
	// find this by clicking Settings on https://bugsnag.com/.
	APIKey string

	// Deprecated: Use Endpoints (with an 's') instead.
	// The Endpoint to notify about crashes. This defaults to
	// "https://notify.bugsnag.com/", if you're using Bugsnag Enterprise then
	// set it to your internal Bugsnag endpoint.
	Endpoint string
	// Endpoints define the HTTP endpoints that the notifier should notify
	// about crashes and sessions. These default to notify.bugsnag.com for
	// error reports and sessions.bugsnag.com for sessions.
	// If you are using bugsnag on-premise you will have to set these to your
	// Event Server and Session Server endpoints. If the notify endpoint is set
	// but the sessions endpoint is not, session tracking will be disabled
	// automatically to avoid leaking session information outside of your
	// server configuration, and a warning will be logged.
	Endpoints Endpoints

	// The current release stage. This defaults to "production" and is used to
	// filter errors in the Bugsnag dashboard.
	ReleaseStage string
	// A specialized type of the application, such as the worker queue or web
	// framework used, like "rails", "mailman", or "celery"
	AppType string
	// The currently running version of the app. This is used to filter errors
	// in the Bugsnag dashboard. If you set this then Bugsnag will only re-open
	// resolved errors if they happen in different app versions.
	AppVersion string

	// AutoCaptureSessions can be set to false to disable automatic session
	// tracking. If you want control over what is deemed a session, you can
	// switch off automatic session tracking with this configuration, and call
	// bugsnag.StartSession() when appropriate for your application. See the
	// official docs for instructions and examples of associating handled
	// errors with sessions and ensuring error rate accuracy on the Bugsnag
	// dashboard. This will default to true, but is stored as an interface to enable
	// us to detect when this option has not been set.
	AutoCaptureSessions interface{}

	// The hostname of the current server. This defaults to the return value of
	// os.Hostname() and is graphed in the Bugsnag dashboard.
	Hostname string

	// The Release stages to notify in. If you set this then bugsnag-go will
	// only send notifications to Bugsnag if the ReleaseStage is listed here.
	NotifyReleaseStages []string

	// packages that are part of your app. Bugsnag uses this to determine how
	// to group errors and how to display them on your dashboard. You should
	// include any packages that are part of your app, and exclude libraries
	// and helpers. You can list wildcards here, and they'll be expanded using
	// filepath.Glob. The default value is []string{"main*"}
	ProjectPackages []string

	// The SourceRoot is the directory where the application is built, and the
	// assumed prefix of lines on the stacktrace originating in the parent
	// application. When set, the prefix is trimmed from callstack file names
	// before ProjectPackages for better readability and to better group errors
	// on the Bugsnag dashboard. The default value is $GOPATH/src or $GOROOT/src
	// if $GOPATH is unset. At runtime, $GOROOT is the root used during the Go
	// build.
	SourceRoot string

	// Any meta-data that matches these filters will be marked as [FILTERED]
	// before sending a Notification to Bugsnag. It defaults to
	// []string{"password", "secret"} so that request parameters like password,
	// password_confirmation and auth_secret will not be sent to Bugsnag.
	ParamsFilters []string

	// The PanicHandler is used by Bugsnag to catch unhandled panics in your
	// application. The default panicHandler uses mitchellh's panicwrap library,
	// and you can disable this feature by passing an empty: func() {}
	PanicHandler func()

	// The logger that Bugsnag should log to. Uses the same defaults as go's
	// builtin logging package. bugsnag-go logs whenever it notifies Bugsnag
	// of an error, and when any error occurs inside the library itself.
	Logger interface {
		Printf(format string, v ...interface{}) // limited to the functions used
	}
	// The http Transport to use, defaults to the default http Transport. This
	// can be configured if you are in an environment
	// that has stringent conditions on making http requests.
	Transport http.RoundTripper
	// Whether bugsnag should notify synchronously. This defaults to false which
	// causes bugsnag-go to spawn a new goroutine for each notification.
	Synchronous bool
	// contains filtered or unexported fields
}

Configuration sets up and customizes communication with the Bugsnag API.

var Config Configuration

Config is the configuration for the default bugsnag notifier.

func (*Configuration) IsAutoCaptureSessions added in v1.4.0

func (config *Configuration) IsAutoCaptureSessions() bool

IsAutoCaptureSessions identifies whether or not the notifier should automatically capture sessions as requests come in. It's a convenience wrapper that allows automatic session capturing to be enabled by default.

type Context

type Context struct {
	String string
}

Context is the context of the error in Bugsnag. This can be passed to Notify, Recover or AutoNotify as rawData.

type Endpoints added in v1.4.0

type Endpoints struct {
	Sessions string
	Notify   string
}

Endpoints hold the HTTP endpoints of the notifier.

type ErrorClass added in v1.0.4

type ErrorClass struct {
	Name string
}

ErrorClass overrides the error class in Bugsnag. This struct enables you to group errors as you like.

type Event

type Event struct {

	// The original error that caused this event, not sent to Bugsnag.
	Error *errors.Error

	// The rawData affecting this error, not sent to Bugsnag.
	RawData []interface{}

	// The error class to be sent to Bugsnag. This defaults to the type name of the Error, for
	// example *error.String
	ErrorClass string
	// The error message to be sent to Bugsnag. This defaults to the return value of Error.Error()
	Message string
	// The stacktrrace of the error to be sent to Bugsnag.
	Stacktrace []StackFrame

	// The context to be sent to Bugsnag. This should be set to the part of the app that was running,
	// e.g. for http requests, set it to the path.
	Context string
	// The severity of the error. Can be SeverityError, SeverityWarning or SeverityInfo.
	Severity severity
	// The grouping hash is used to override Bugsnag's grouping. Set this if you'd like all errors with
	// the same grouping hash to group together in the dashboard.
	GroupingHash string

	// User data to send to Bugsnag. This is searchable on the dashboard.
	User *User
	// Other MetaData to send to Bugsnag. Appears as a set of tabbed tables in the dashboard.
	MetaData MetaData
	// Ctx is the context of the session the event occurred in. This allows Bugsnag to associate the event with the session.
	Ctx context.Context
	// Request is the request information that populates the Request tab in the dashboard.
	Request *RequestJSON

	// True if the event was caused by an automatic event
	Unhandled bool
	// contains filtered or unexported fields
}

Event represents a payload of data that gets sent to Bugsnag. This is passed to each OnBeforeNotify hook.

type HandledState added in v1.3.0

type HandledState struct {
	SeverityReason   SeverityReason
	OriginalSeverity severity
	Unhandled        bool
	Framework        string
}

type MetaData

type MetaData map[string]map[string]interface{}

MetaData is added to the Bugsnag dashboard in tabs. Each tab is a map of strings -> values. You can pass MetaData to Notify, Recover and AutoNotify as rawData.

Example
notifier.Notify(errors.Errorf("hi world"),
	MetaData{"Account": {
		"id":      account.ID,
		"name":    account.Name,
		"paying?": account.Plan.Premium,
	}})
Output:

func (MetaData) Add

func (meta MetaData) Add(tab string, key string, value interface{})

Add creates a tab of Bugsnag meta-data. If the tab doesn't yet exist it will be created. If the key already exists, it will be overwritten.

func (MetaData) AddStruct

func (meta MetaData) AddStruct(tab string, obj interface{})

AddStruct creates a tab of Bugsnag meta-data. The struct will be converted to an Object using the reflect library so any private fields will not be exported. As a safety measure, if you pass a non-struct the value will be sent to Bugsnag under the "Extra data" tab.

func (MetaData) Update

func (meta MetaData) Update(other MetaData)

Update the meta-data with more information. Tabs are merged together such that unique keys from both sides are preserved, and duplicate keys end up with the provided values.

type Notifier

type Notifier struct {
	Config  *Configuration
	RawData []interface{}
}

Notifier sends errors to Bugsnag.

func New

func New(rawData ...interface{}) *Notifier

New creates a new notifier. You can pass an instance of bugsnag.Configuration in rawData to change the configuration. Other values of rawData will be passed to Notify.

func (*Notifier) AutoNotify

func (notifier *Notifier) AutoNotify(rawData ...interface{})

AutoNotify notifies Bugsnag of any panics, then repanics. It sends along any rawData that gets passed in. Usage:

 go func() {
		defer AutoNotify()
     // (possibly crashy code)
 }()

func (*Notifier) FlushSessionsOnRepanic added in v1.4.0

func (notifier *Notifier) FlushSessionsOnRepanic(shouldFlush bool)

FlushSessionsOnRepanic takes a boolean that indicates whether sessions should be flushed when AutoNotify repanics. In the case of a fatal panic the sessions might not get sent to Bugsnag before the application shuts down. Many frameworks will have their own error handler, and for these frameworks there is no need to flush sessions as the application will survive the panic and the sessions can be sent off later. The default value is true, so this needs only be called if you wish to inform Bugsnag that there is an error handler that will take care of panics that AutoNotify will re-raise.

func (*Notifier) Notify

func (notifier *Notifier) Notify(err error, rawData ...interface{}) (e error)

Notify sends an error to Bugsnag. Any rawData you pass here will be sent to Bugsnag after being converted to JSON. e.g. bugsnag.SeverityError, bugsnag.Context, or bugsnag.MetaData. Any bools in rawData overrides the notifier.Config.Synchronous flag.

func (*Notifier) NotifySync added in v1.2.1

func (notifier *Notifier) NotifySync(err error, sync bool, rawData ...interface{}) error

NotifySync sends an error to Bugsnag. A boolean parameter specifies whether to send the report in the current context (by default false, i.e. asynchronous). Any other rawData you pass here will be sent to Bugsnag after being converted to JSON. E.g. bugsnag.SeverityError, bugsnag.Context, or bugsnag.MetaData.

func (*Notifier) Recover

func (notifier *Notifier) Recover(rawData ...interface{})

Recover logs any panics, then recovers. It sends along any rawData that gets passed in. Usage: defer Recover()

type RequestJSON added in v1.4.0

type RequestJSON struct {
	ClientIP   string            `json:"clientIp,omitempty"`
	Headers    map[string]string `json:"headers,omitempty"`
	HTTPMethod string            `json:"httpMethod,omitempty"`
	URL        string            `json:"url,omitempty"`
	Referer    string            `json:"referer,omitempty"`
}

RequestJSON is the request information that populates the Request tab in the dashboard.

type SeverityReason added in v1.3.0

type SeverityReason string

type StackFrame added in v1.6.0

type StackFrame struct {
	Method     string `json:"method"`
	File       string `json:"file"`
	LineNumber int    `json:"lineNumber"`
	InProject  bool   `json:"inProject,omitempty"`
}

The form of stacktrace that Bugsnag expects

type User

type User struct {
	Id    string `json:"id,omitempty"`
	Name  string `json:"name,omitempty"`
	Email string `json:"email,omitempty"`
}

User represents the searchable user-data on Bugsnag. The Id is also used to determine the number of users affected by a bug. This can be passed to Notify, Recover or AutoNotify as rawData.

Directories

Path Synopsis
Package errors provides errors that have stack-traces.
Package errors provides errors that have stack-traces.
examples
features
Package bugsnagmartini provides a martini middleware that sends panics to Bugsnag.
Package bugsnagmartini provides a martini middleware that sends panics to Bugsnag.
Package bugsnagrevel adds Bugsnag to revel.
Package bugsnagrevel adds Bugsnag to revel.
Package testutil can be .-imported to gain access to useful test functions.
Package testutil can be .-imported to gain access to useful test functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL