logrus/hooks/bugsnag/bugsnag.go

69 lines
1.9 KiB
Go
Raw Permalink Normal View History

2015-03-16 22:29:39 +03:00
package logrus_bugsnag
import (
2015-03-19 18:17:22 +03:00
"errors"
2015-03-16 22:29:39 +03:00
"github.com/Sirupsen/logrus"
"github.com/bugsnag/bugsnag-go"
)
2015-03-19 18:17:22 +03:00
type bugsnagHook struct{}
// ErrBugsnagUnconfigured is returned if NewBugsnagHook is called before
// bugsnag.Configure. Bugsnag must be configured before the hook.
var ErrBugsnagUnconfigured = errors.New("bugsnag must be configured before installing this logrus hook")
// ErrBugsnagSendFailed indicates that the hook failed to submit an error to
// bugsnag. The error was successfully generated, but `bugsnag.Notify()`
// failed.
type ErrBugsnagSendFailed struct {
err error
}
func (e ErrBugsnagSendFailed) Error() string {
return "failed to send error to Bugsnag: " + e.err.Error()
}
// NewBugsnagHook initializes a logrus hook which sends exceptions to an
// exception-tracking service compatible with the Bugsnag API. Before using
// this hook, you must call bugsnag.Configure(). The returned object should be
// registered with a log via `AddHook()`
2015-03-16 22:29:39 +03:00
//
// Entries that trigger an Error, Fatal or Panic should now include an "error"
2015-03-19 18:17:22 +03:00
// field to send to Bugsnag.
func NewBugsnagHook() (*bugsnagHook, error) {
if bugsnag.Config.APIKey == "" {
return nil, ErrBugsnagUnconfigured
2015-03-16 22:29:39 +03:00
}
2015-03-19 18:17:22 +03:00
return &bugsnagHook{}, nil
}
2015-03-16 22:29:39 +03:00
2015-03-19 18:17:22 +03:00
// Fire forwards an error to Bugsnag. Given a logrus.Entry, it extracts the
// "error" field (or the Message if the error isn't present) and sends it off.
func (hook *bugsnagHook) Fire(entry *logrus.Entry) error {
var notifyErr error
2015-03-16 22:29:39 +03:00
err, ok := entry.Data["error"].(error)
2015-03-19 18:17:22 +03:00
if ok {
notifyErr = err
} else {
notifyErr = errors.New(entry.Message)
2015-03-16 22:29:39 +03:00
}
2015-03-19 18:17:22 +03:00
bugsnagErr := bugsnag.Notify(notifyErr)
2015-03-16 22:29:39 +03:00
if bugsnagErr != nil {
2015-03-19 18:17:22 +03:00
return ErrBugsnagSendFailed{bugsnagErr}
2015-03-16 22:29:39 +03:00
}
return nil
}
// Levels enumerates the log levels on which the error should be forwarded to
// bugsnag: everything at or above the "Error" level.
2015-03-19 18:17:22 +03:00
func (hook *bugsnagHook) Levels() []logrus.Level {
2015-03-16 22:29:39 +03:00
return []logrus.Level{
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
}