rollbar

package module
Version: v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2020 License: MIT Imports: 18 Imported by: 72

README

rollbar-go

Build Status

Rollbar is a real-time exception reporting service for Go and other languages. The Rollbar service will alert you of problems with your code and help you understand them in a ways never possible before. We love it and we hope you will too.

rollbar-go is a Golang Rollbar client that makes it easy to report errors to Rollbar with full stacktraces. Errors are sent to Rollbar asynchronously in a background goroutine.

Because Go's error type doesn't include stack information from when it was set or allocated, we use the stack information from where the error was reported.

Setup Instructions and Usage

  1. Sign up for a Rollbar account
  2. Follow the Usage example in our Go SDK docs to get started for your platform.

Documentation

API docs on godoc.org

Running Tests

Running tests docs on docs.rollar.com

Release History & Changelog

See our Releases page for a list of all releases, including changes.

Help / Support

If you run into any issues, please email us at support@rollbar.com

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature).
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

History

This library originated with this project github.com/stvp/rollbar. This was subsequently forked by Heroku, github.com/heroku/rollbar, and extended. Those two libraries diverged as features were added independently to both. This official library is actually a fork of the Heroku fork with some git magic to make it appear as a standalone repository along with all of that history. We then also went back to the original stvp library and brought over most of the divergent changes. Since then we have moved forward to add more functionality to this library and it is the recommended notifier for Go going forward.

Documentation

Overview

Package rollbar is a Golang Rollbar client that makes it easy to report errors to Rollbar with full stacktraces.

Basic Usage

This package is designed to be used via the functions exposed at the root of the `rollbar` package. These work by managing a single instance of the `Client` type that is configurable via the setter functions at the root of the package.

package main

import (
  "github.com/rollbar/rollbar-go"
  "time"
)

func main() {
  rollbar.SetToken("MY_TOKEN")
  rollbar.SetEnvironment("production") // defaults to "development"
  rollbar.SetCodeVersion("v2")         // optional Git hash/branch/tag (required for GitHub integration)
  rollbar.SetServerHost("web.1")       // optional override; defaults to hostname
  rollbar.SetServerRoot("/")           // local path of project (required for GitHub integration and non-project stacktrace collapsing)

  rollbar.Info("Message body goes here")
  rollbar.WrapAndWait(doSomething)
}

func doSomething() {
  var timer *time.Timer = nil
  timer.Reset(10) // this will panic
}

If you wish for more fine grained control over the client or you wish to have multiple independent clients then you can create and manage your own instances of the `Client` type.

We provide two implementations of the `Transport` interface, `AsyncTransport` and `SyncTransport`. These manage the communication with the network layer. The Async version uses a buffered channel to communicate with the Rollbar API in a separate go routine. The Sync version is fully synchronous. It is possible to create your own `Transport` and configure a Client to use your preferred implementation.

Handling Panics

Go does not provide a mechanism for handling all panics automatically, therefore we provide two functions `Wrap` and `WrapAndWait` to make working with panics easier. They both take a function with arguments and then report to Rollbar if that function panics. They use the recover mechanism to capture the panic, and therefore if you wish your process to have the normal behaviour on panic (i.e. to crash), you will need to re-panic the result of calling `Wrap`. For example,

package main

import (
  "errors"
  "github.com/rollbar/rollbar-go"
)

func PanickyFunction(arg string) string {
  panic(errors.New("AHHH!!!!"))
  return arg
}

func main() {
  rollbar.SetToken("MY_TOKEN")
  err := rollbar.Wrap(PanickyFunction, "function arg1")
  if err != nil {
    // This means our function panic'd
    // Uncomment the next line to get normal
    // crash on panic behaviour
    // panic(err)
  }
  rollbar.Wait()
}

The above pattern of calling `Wrap(...)` and then `Wait(...)` can be combined via `WrapAndWait(...)`. When `WrapAndWait(...)` returns if there was a panic it has already been sent to the Rollbar API. The error is still returned by this function if there is one.

`Wrap` and `WrapAndWait` will accept functions with any number and type of arguments and return values. However, they do not return the function's return value, instead returning the error value. To add Rollbar panic handling to a function while preserving access to the function's return values, we provide the `LogPanic` helper designed to be used inside your deferred function.

func PanickyFunction(arg string) string {
  defer func() {
    err := recover()
    rollbar.LogPanic(err, true) // bool argument sets wait behavior
  }()

  panic(errors.New("AHHH!!!!"))
  return arg
}

This offers virtually the same functionality as `Wrap` and `WrapAndWait` while preserving access to the function return values.

Tracing Errors

Due to the nature of the `error` type in Go, it can be difficult to attribute errors to their original origin without doing some extra work. To account for this, we provide multiple ways of configuring the client to unwrap errors and extract stack traces.

The client will automatically unwrap any error type which implements the `Unwrap() error` method specified in Go 1.13. (See https://golang.org/pkg/errors/ for details.) This behavior can be extended for other types of errors by calling `SetUnwrapper`.

For stack traces, we provide the `Stacker` interface, which can be implemented on custom error types:

type Stacker interface {
  Stack() []runtime.Frame
}

If you cannot implement the `Stacker` interface on your error type (which is common for third-party error libraries), you can provide a custom tracing function by calling `SetStackTracer`.

See the documentation of `SetUnwrapper` and `SetStackTracer` for more information and examples.

Finally, users of github.com/pkg/errors can use the utilities provided in the `errors` sub-package.

Index

Examples

Constants

View Source
const (
	// CaptureIpFull means capture the entire address without any modification.
	CaptureIpFull captureIp = iota
	// CaptureIpAnonymize means apply a pseudo-anonymization.
	CaptureIpAnonymize
	// CaptureIpNone means do not capture anything.
	CaptureIpNone
)
View Source
const (
	// NAME is the name of this notifier sent with the payload to Rollbar.
	NAME = "rollbar/rollbar-go"
	// VERSION is the version of this notifier sent with the payload to Rollbar.
	VERSION = "1.2.0"

	// CRIT is the critial severity level.
	CRIT = "critical"
	// ERR is the error severity level.
	ERR = "error"
	// WARN is the warning severity level.
	WARN = "warning"
	// INFO is the info severity level.
	INFO = "info"
	// DEBUG is the debug severity level.
	DEBUG = "debug"

	// FILTERED is the string used to replace values that are scrubbed based on the configured headers
	// and fields used for scrubbing.
	FILTERED = "[FILTERED]"
)
View Source
const (
	// DefaultBuffer is the default size of the buffered channel used
	// for queueing items to send to Rollbar in the asynchronous
	// implementation of Transport.
	DefaultBuffer = 1000
	// DefaultRetryAttempts is the number of times we attempt to retry sending an item when
	// encountering temporary network errors
	DefaultRetryAttempts = 3
)

Variables

This section is empty.

Functions

func CaptureIp

func CaptureIp() captureIp

CaptureIp is the currently set level of IP address information to capture from requests.

func ClearPerson

func ClearPerson()

ClearPerson clears any previously set person information. See `SetPerson` for more information.

func Close

func Close()

Close will block until the queue of errors / messages is empty and terminate the goroutine used for sending items.

func CodeVersion

func CodeVersion() string

CodeVersion is the string describing the running code version on the server that is currently set on the managed Client instance.

func Critical

func Critical(interfaces ...interface{})

Critical reports an item with level `critical`. This function recognizes arguments with the following types:

*http.Request
error
string
map[string]interface{}
int

The string and error types are mutually exclusive. If an error is present then a stack trace is captured. If an int is also present then we skip that number of stack frames. If the map is present it is used as extra custom data in the item. If a string is present without an error, then we log a message without a stack trace. If a request is present we extract as much relevant information from it as we can.

Example (Error)
rollbar.Critical(errors.New("bork"), map[string]interface{}{
	"hello": "world",
})
Output:

Example (Message)
rollbar.Critical("bork", map[string]interface{}{
	"hello": "world",
})
Output:

func Custom

func Custom() map[string]interface{}

Custom is the currently set extra metadata on the managed Client instance.

func Debug

func Debug(interfaces ...interface{})

Debug reports an item with level `debug`. This function recognizes arguments with the following types:

*http.Request
error
string
map[string]interface{}
int

The string and error types are mutually exclusive. If an error is present then a stack trace is captured. If an int is also present then we skip that number of stack frames. If the map is present it is used as extra custom data in the item. If a string is present without an error, then we log a message without a stack trace. If a request is present we extract as much relevant information from it as we can.

Example (Error)
rollbar.Debug(errors.New("bork"), map[string]interface{}{
	"hello": "world",
})
Output:

Example (Message)
rollbar.Debug("bork", map[string]interface{}{
	"hello": "world",
})
Output:

func Endpoint

func Endpoint() string

Endpoint is the currently configured endpoint to send items on the managed Client instance.

func Environment

func Environment() string

Environment is the environment currently set on the managed Client instance.

func Error

func Error(interfaces ...interface{})

Error reports an item with level `error`. This function recognizes arguments with the following types:

*http.Request
error
string
map[string]interface{}
int

The string and error types are mutually exclusive. If an error is present then a stack trace is captured. If an int is also present then we skip that number of stack frames. If the map is present it is used as extra custom data in the item. If a string is present without an error, then we log a message without a stack trace. If a request is present we extract as much relevant information from it as we can.

Example (Error)
rollbar.Error(errors.New("bork"), map[string]interface{}{
	"hello": "world",
})
Output:

Example (Message)
rollbar.Error("bork", map[string]interface{}{
	"hello": "world",
})
Output:

func ErrorWithExtras

func ErrorWithExtras(level string, err error, extras map[string]interface{})

ErrorWithExtras asynchronously sends an error to Rollbar with the given severity level with extra custom data.

func ErrorWithExtrasAndContext

func ErrorWithExtrasAndContext(ctx context.Context, level string, err error, extras map[string]interface{})

ErrorWithExtrasAndContext asynchronously sends an error to Rollbar with the given severity level with extra custom data, within the given context.

func ErrorWithLevel

func ErrorWithLevel(level string, err error)

ErrorWithLevel asynchronously sends an error to Rollbar with the given severity level.

func ErrorWithStackSkip

func ErrorWithStackSkip(level string, err error, skip int)

ErrorWithStackSkip asynchronously sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped.

func ErrorWithStackSkipWithExtras

func ErrorWithStackSkipWithExtras(level string, err error, skip int, extras map[string]interface{})

ErrorWithStackSkipWithExtras asynchronously sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped with extra custom data.

func ErrorWithStackSkipWithExtrasAndContext

func ErrorWithStackSkipWithExtrasAndContext(ctx context.Context, level string, err error, skip int, extras map[string]interface{})

ErrorWithStackSkipWithExtrasAndContext asynchronously sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped with extra custom data, within the given context.

func Errorf

func Errorf(level string, format string, args ...interface{})

Errorf sends an error to Rollbar with the given level using the format string and arguments.

func Fingerprint

func Fingerprint() bool

Fingerprint is whether or not the current managed Client instance uses a custom client-side fingerprint. The default is false.

func Info

func Info(interfaces ...interface{})

Info reports an item with level `info`. This function recognizes arguments with the following types:

*http.Request
error
string
map[string]interface{}
int

The string and error types are mutually exclusive. If an error is present then a stack trace is captured. If an int is also present then we skip that number of stack frames. If the map is present it is used as extra custom data in the item. If a string is present without an error, then we log a message without a stack trace. If a request is present we extract as much relevant information from it as we can.

Example (Error)
rollbar.Info(errors.New("bork"), map[string]interface{}{
	"hello": "world",
})
Output:

Example (Message)
rollbar.Info("bork", map[string]interface{}{
	"hello": "world",
})
Output:

func LambdaWrapper

func LambdaWrapper(handlerFunc interface{}) interface{}

LambdaWrapper calls handlerFunc with arguments, and recovers and reports a panic to Rollbar if it occurs. This functions as a passthrough wrapper for lambda.Start(). This also waits before returning to ensure all messages completed.

func Log

func Log(level string, interfaces ...interface{})

Log reports an item with the given level. This function recognizes arguments with the following types:

*http.Request
error
string
map[string]interface{}
int

The string and error types are mutually exclusive. If an error is present then a stack trace is captured. If an int is also present then we skip that number of stack frames. If the map is present it is used as extra custom data in the item. If a string is present without an error, then we log a message without a stack trace. If a request is present we extract as much relevant information from it as we can.

func LogPanic

func LogPanic(err interface{}, wait bool)

LogPanic accepts an error value returned by recover() and handles logging to Rollbar with stack info.

func Message

func Message(level string, msg string)

Message asynchronously sends a message to Rollbar with the given severity level. Rollbar request is asynchronous.

func MessageWithExtras

func MessageWithExtras(level string, msg string, extras map[string]interface{})

MessageWithExtras asynchronously sends a message to Rollbar with the given severity level with extra custom data. Rollbar request is asynchronous.

func MessageWithExtrasAndContext

func MessageWithExtrasAndContext(ctx context.Context, level string, msg string, extras map[string]interface{})

MessageWithExtrasAndContext asynchronously sends a message to Rollbar with the given severity level with extra custom data, within the given context. Rollbar request is asynchronous.

func NewPersonContext

func NewPersonContext(ctx context.Context, p *Person) context.Context

NewPersonContext returns a new Context that carries the person as a value.

func Platform

func Platform() string

Platform is the platform reported for all Rollbar items. The default is the running operating system (darwin, freebsd, linux, etc.) but it can also be application specific (client, heroku, etc.).

func RequestError

func RequestError(level string, r *http.Request, err error)

RequestError asynchronously sends an error to Rollbar with the given severity level and request-specific information.

func RequestErrorWithExtras

func RequestErrorWithExtras(level string, r *http.Request, err error, extras map[string]interface{})

RequestErrorWithExtras asynchronously sends an error to Rollbar with the given severity level and request-specific information with extra custom data.

func RequestErrorWithExtrasAndContext

func RequestErrorWithExtrasAndContext(ctx context.Context, level string, r *http.Request, err error, extras map[string]interface{})

RequestErrorWithExtrasAndContext asynchronously sends an error to Rollbar with the given severity level and request-specific information with extra custom data.

func RequestErrorWithStackSkip

func RequestErrorWithStackSkip(level string, r *http.Request, err error, skip int)

RequestErrorWithStackSkip asynchronously sends an error to Rollbar with the RequestErrorWithStackSkip asynchronously sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped, in addition to extra request-specific information.

func RequestErrorWithStackSkipWithExtras

func RequestErrorWithStackSkipWithExtras(level string, r *http.Request, err error, skip int, extras map[string]interface{})

RequestErrorWithStackSkipWithExtras asynchronously sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped, in addition to extra request-specific information and extra custom data.

func RequestErrorWithStackSkipWithExtrasAndContext

func RequestErrorWithStackSkipWithExtrasAndContext(ctx context.Context, level string, r *http.Request, err error, skip int, extras map[string]interface{})

RequestErrorWithStackSkipWithExtrasAndContext asynchronously sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped, in addition to extra request-specific information and extra custom data, within the given context.

func RequestMessage

func RequestMessage(level string, r *http.Request, msg string)

RequestMessage asynchronously sends a message to Rollbar with the given severity level and request-specific information.

func RequestMessageWithExtras

func RequestMessageWithExtras(level string, r *http.Request, msg string, extras map[string]interface{})

RequestMessageWithExtras asynchronously sends a message to Rollbar with the given severity level with extra custom data in addition to extra request-specific information. Rollbar request is asynchronous.

func RequestMessageWithExtrasAndContext

func RequestMessageWithExtrasAndContext(ctx context.Context, level string, r *http.Request, msg string, extras map[string]interface{})

RequestMessageWithExtrasAndContext asynchronously sends a message to Rollbar with the given severity level with extra custom data in addition to extra request-specific information, within the given context. Rollbar request is asynchronous.

func ServerHost

func ServerHost() string

ServerHost is the currently set hostname on the managed Client instance. The value will be indexed.

func ServerRoot

func ServerRoot() string

ServerRoot is the currently set path to the code root set on the managed Client instance. This should be a path to the application code root, not including the final slash. It is used to collapse non-project code when displaying tracebacks.

func SetCaptureIp

func SetCaptureIp(captureIp captureIp)

SetCaptureIp sets what level of IP address information to capture from requests. CaptureIpFull means capture the entire address without any modification. CaptureIpAnonymize means apply a pseudo-anonymization. CaptureIpNone means do not capture anything.

func SetCheckIgnore

func SetCheckIgnore(checkIgnore func(string) bool)

SetCheckIgnore sets the checkIgnore function on the managed Client instance. CheckIgnore is called during the recovery process of a panic that occurred inside a function wrapped by Wrap or WrapAndWait. Return true if you wish to ignore this panic, false if you wish to report it to Rollbar. If an error is the argument to the panic, then this function is called with the result of calling Error(), otherwise the string representation of the value is passed to this function.

func SetCodeVersion

func SetCodeVersion(codeVersion string)

SetCodeVersion sets the code version on the managed Client instance. The code version is a string describing the running code version on the server.

func SetCustom

func SetCustom(custom map[string]interface{})

SetCustom sets custom data on the managed Client instance. The data set is any arbitrary metadata you want to send with every subsequently sent item.

func SetEnabled

func SetEnabled(enabled bool)

SetEnabled sets whether or not the managed Client instance is enabled. If this is true then this library works as normal. If this is false then no calls will be made to the network. One place where this is useful is for turning off reporting in tests.

func SetEndpoint

func SetEndpoint(endpoint string)

SetEndpoint sets the endpoint on the managed Client instance. The endpoint to post items to. The default value is https://api.rollbar.com/api/1/item/

func SetEnvironment

func SetEnvironment(environment string)

SetEnvironment sets the environment on the managed Client instance. All errors and messages will be submitted under this environment.

func SetFingerprint

func SetFingerprint(fingerprint bool)

SetFingerprint sets whether or not to use custom client-side fingerprinting on the managed Client instance. This custom fingerprinting is based on a CRC32 checksum. The alternative is to let the server compute a fingerprint for each item. The default is false.

func SetHTTPClient

func SetHTTPClient(httpClient *http.Client)

SetHTTPClient sets custom http client. http.DefaultClient is used by default

func SetLogger

func SetLogger(logger ClientLogger)

SetLogger sets an alternative logger to be used by the underlying transport layer on the managed Client instance.

func SetPerson

func SetPerson(id, username, email string)

SetPerson information for identifying a user associated with any subsequent errors or messages. Only id is required to be non-empty.

func SetPlatform

func SetPlatform(platform string)

SetPlatform sets the platform on the managed Client instance. The platform is reported for all Rollbar items. The default is the running operating system (darwin, freebsd, linux, etc.) but it can also be application specific (client, heroku, etc.).

func SetPrintPayloadOnError

func SetPrintPayloadOnError(printPayloadOnError bool)

SetPrintPayloadOnError sets whether or not to output the payload to stderr if an error occurs during transport to the Rollbar API. For example, if you hit your rate limit and we run out of retry attempts, then if this is true we will output the item to stderr rather than the item disappearing completely. By default this is true.

func SetRetryAttempts

func SetRetryAttempts(retryAttempts int)

SetRetryAttempts sets how many times to attempt to retry sending an item if the http transport experiences temporary error conditions. By default this is equal to DefaultRetryAttempts. Temporary errors include timeouts and rate limit responses.

func SetScrubFields

func SetScrubFields(fields *regexp.Regexp)

SetScrubFields sets the fields to scrub on the managed Client instance. The value is a regular expression to match keys in the item payload for scrubbing. The default vlaue is regexp.MustCompile("password|secret|token").

func SetScrubHeaders

func SetScrubHeaders(headers *regexp.Regexp)

SetScrubHeaders sets the headers to scrub on the managed Client instance. The value is a regular expression used to match headers for scrubbing. The default value is regexp.MustCompile("Authorization").

func SetServerHost

func SetServerHost(serverHost string)

SetServerHost sets the host value on the managed Client instance. Server host is the hostname sent with all Rollbar items. The value will be indexed.

func SetServerRoot

func SetServerRoot(serverRoot string)

SetServerRoot sets the code root value on the managed Client instance. Path to the application code root, not including the final slash. Used to collapse non-project code when displaying tracebacks.

func SetStackTracer

func SetStackTracer(stackTracer StackTracerFunc)

SetStackTracer sets the StackTracerFunc used by the managed Client instance. The stack tracer function is used to extract the stack trace from enhanced error types. This feature can be used to add support for custom error types that do not implement the Stacker interface. See the documentation of StackTracerFunc for more details.

In order to preserve the default stack tracing behavior, callers of SetStackTracer may wish to include a call to DefaultStackTracer in their custom tracing function. See the provided example.

Example
package main

import (
	"runtime"

	"github.com/rollbar/rollbar-go"
)

type CustomTraceError struct {
	error
	trace []runtime.Frame
}

func (e CustomTraceError) GetTrace() []runtime.Frame {
	return e.trace
}

func main() {
	rollbar.SetStackTracer(func(err error) ([]runtime.Frame, bool) {
		// preserve the default behavior for other types of errors
		if trace, ok := rollbar.DefaultStackTracer(err); ok {
			return trace, ok
		}

		if cerr, ok := err.(CustomTraceError); ok {
			return cerr.GetTrace(), true
		}

		return nil, false
	})
}
Output:

func SetToken

func SetToken(token string)

SetToken sets the token on the managed Client instance. The value is a Rollbar access token with scope "post_server_item". It is required to set this value before any of the other functions herein will be able to work properly.

func SetTransform

func SetTransform(transform func(map[string]interface{}))

SetTransform sets the transform function called after the entire payload has been built before it is sent to the API. The structure of the final payload sent to the API is:

{
    "access_token": "YOUR_ACCESS_TOKEN",
    "data": { ... }
}

This function takes a map[string]interface{} which is the value of the data key in the payload described above. You can modify this object in-place to make any arbitrary changes you wish to make before it is finally sent. Be careful with the modifications you make as they could lead to the payload being malformed from the perspective of the API.

func SetUnwrapper

func SetUnwrapper(unwrapper UnwrapperFunc)

SetUnwrapper sets the UnwrapperFunc used by the managed Client instance. The unwrapper function is used to extract wrapped errors from enhanced error types. This feature can be used to add support for custom error types that do not yet implement the Unwrap method specified in Go 1.13. See the documentation of UnwrapperFunc for more details.

In order to preserve the default unwrapping behavior, callers of SetUnwrapper may wish to include a call to DefaultUnwrapper in their custom unwrapper function. See the provided example.

Example
package main

import "github.com/rollbar/rollbar-go"

type CustomWrappingError struct {
	error
	wrapped error
}

func (e CustomWrappingError) GetWrappedError() error {
	return e.wrapped
}

func main() {
	rollbar.SetUnwrapper(func(err error) error {
		// preserve the default behavior for other types of errors
		if unwrapped := rollbar.DefaultUnwrapper(err); unwrapped != nil {
			return unwrapped
		}

		if ex, ok := err.(CustomWrappingError); ok {
			return ex.GetWrappedError()
		}

		return nil
	})
}
Output:

func Token

func Token() string

Token returns the currently set Rollbar access token on the managed Client instance.

func Wait

func Wait()

Wait will block until the queue of errors / messages is empty.

func Warning

func Warning(interfaces ...interface{})

Warning reports an item with level `warning`. This function recognizes arguments with the following types:

*http.Request
error
string
map[string]interface{}
int

The string and error types are mutually exclusive. If an error is present then a stack trace is captured. If an int is also present then we skip that number of stack frames. If the map is present it is used as extra custom data in the item. If a string is present without an error, then we log a message without a stack trace. If a request is present we extract as much relevant information from it as we can.

Example (Error)
rollbar.Warning(errors.New("bork"), map[string]interface{}{
	"hello": "world",
})
Output:

Example (Message)
rollbar.Warning("bork", map[string]interface{}{
	"hello": "world",
})
Output:

func Wrap

func Wrap(f interface{}, args ...interface{}) interface{}

Wrap calls f and then recovers and reports a panic to Rollbar if it occurs. If an error is captured it is subsequently returned.

func WrapAndWait

func WrapAndWait(f interface{}, args ...interface{}) interface{}

WrapAndWait calls f, and recovers and reports a panic to Rollbar if it occurs. This also waits before returning to ensure the message was reported. If an error is captured it is subsequently returned.

func WrapWithArgs

func WrapWithArgs(f interface{}, wait bool, args ...interface{}) interface{}

WrapWithArgs calls f with the supplied args and reports a panic to Rollbar if it occurs. If wait is true, this also waits before returning to ensure the message was reported. If an error is captured it is subsequently returned. WrapWithArgs is compatible with any return type for f, but does not return its return value(s).

Types

type AsyncTransport

type AsyncTransport struct {

	// Buffer is the size of the channel used for queueing asynchronous payloads for sending to
	// Rollbar.
	Buffer int
	// contains filtered or unexported fields
}

AsyncTransport is a concrete implementation of the Transport type which communicates with the Rollbar API asynchronously using a buffered channel.

func NewAsyncTransport

func NewAsyncTransport(token string, endpoint string, buffer int) *AsyncTransport

NewAsyncTransport builds an asynchronous transport which sends data to the Rollbar API at the specified endpoint using the given access token. The channel is limited to the size of the input buffer argument.

func (*AsyncTransport) Close

func (t *AsyncTransport) Close() error

Close is an alias for Wait for the asynchronous transport

func (*AsyncTransport) Send

func (t *AsyncTransport) Send(body map[string]interface{}) error

Send the body to Rollbar if the channel is not currently full. Returns ErrBufferFull if the underlying channel is full.

func (*AsyncTransport) SetEndpoint

func (t *AsyncTransport) SetEndpoint(endpoint string)

SetEndpoint updates the API endpoint to send items to.

func (*AsyncTransport) SetHTTPClient

func (t *AsyncTransport) SetHTTPClient(c *http.Client)

SetHTTPClient sets custom http client. http.DefaultClient is used by default

func (*AsyncTransport) SetLogger

func (t *AsyncTransport) SetLogger(logger ClientLogger)

SetLogger updates the logger that this transport uses for reporting errors that occur while processing items.

func (*AsyncTransport) SetPrintPayloadOnError

func (t *AsyncTransport) SetPrintPayloadOnError(printPayloadOnError bool)

SetPrintPayloadOnError is whether or not to output the payload to stderr if an error occurs during transport to the Rollbar API.

func (*AsyncTransport) SetRetryAttempts

func (t *AsyncTransport) SetRetryAttempts(retryAttempts int)

SetRetryAttempts is how often to attempt to resend an item when a temporary network error occurs This defaults to DefaultRetryAttempts Set this value to 0 if you do not want retries to happen

func (*AsyncTransport) SetToken

func (t *AsyncTransport) SetToken(token string)

SetToken updates the token to use for future API requests.

func (*AsyncTransport) Wait

func (t *AsyncTransport) Wait()

Wait blocks until all of the items currently in the queue have been sent.

type CauseStacker deprecated

This type has been deprecated.
type CauseStacker interface {
	error
	Cause() error
	Stacker
}

CauseStacker is an interface that errors can implement to create a trace_chain.

Deprecated: For unwrapping, use the `Unwrap() error` method specified in Go 1.13. (See https://golang.org/pkg/errors/ for more information). For stack traces, use the `Stacker` interface directly.

type Client

type Client struct {
	io.Closer
	// Transport used to send data to the Rollbar API. By default an asynchronous
	// implementation of the Transport interface is used.
	Transport Transport
	// contains filtered or unexported fields
}

A Client can be used to interact with Rollbar via the configured Transport. The functions at the root of the `rollbar` package are the recommend way of using a Client. One should not need to manage instances of the Client type manually in most normal scenarios. However, if you want to customize the underlying transport layer, or you need to have independent instances of a Client, then you can use the constructors provided for this type.

func New

func New(token, environment, codeVersion, serverHost, serverRoot string) *Client

New returns the default implementation of a Client. This uses the AsyncTransport.

func NewAsync

func NewAsync(token, environment, codeVersion, serverHost, serverRoot string) *Client

NewAsync builds a Client with the asynchronous implementation of the transport interface.

func NewSync

func NewSync(token, environment, codeVersion, serverHost, serverRoot string) *Client

NewSync builds a Client with the synchronous implementation of the transport interface.

func (*Client) CaptureIp

func (c *Client) CaptureIp() captureIp

CaptureIp is the currently set level of IP address information to capture from requests.

func (*Client) ClearPerson

func (c *Client) ClearPerson()

ClearPerson clears any previously set person information. See `SetPerson` for more information.

func (*Client) Close

func (c *Client) Close() error

Close delegates to the Close method of the Transport. For the asynchronous transport this is an alias for Wait, and is a no-op for the synchronous transport.

func (*Client) CodeVersion

func (c *Client) CodeVersion() string

CodeVersion is the currently set string describing the running code version on the server.

func (*Client) Custom

func (c *Client) Custom() map[string]interface{}

Custom is the currently set arbitrary metadata you want to send with every subsequently sent item.

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint is the currently set endpoint used for posting items.

func (*Client) Environment

func (c *Client) Environment() string

Environment is the currently set environment underwhich all errors and messages will be submitted.

func (*Client) ErrorWithExtras

func (c *Client) ErrorWithExtras(level string, err error, extras map[string]interface{})

ErrorWithExtras sends an error to Rollbar with the given severity level with extra custom data.

func (*Client) ErrorWithExtrasAndContext

func (c *Client) ErrorWithExtrasAndContext(ctx context.Context, level string, err error, extras map[string]interface{})

ErrorWithExtrasAndContext sends an error to Rollbar with the given severity level with extra custom data, within the given context.

func (*Client) ErrorWithLevel

func (c *Client) ErrorWithLevel(level string, err error)

ErrorWithLevel sends an error to Rollbar with the given severity level.

func (*Client) ErrorWithStackSkip

func (c *Client) ErrorWithStackSkip(level string, err error, skip int)

ErrorWithStackSkip sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped.

func (*Client) ErrorWithStackSkipWithExtras

func (c *Client) ErrorWithStackSkipWithExtras(level string, err error, skip int, extras map[string]interface{})

ErrorWithStackSkipWithExtras sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped with extra custom data.

func (*Client) ErrorWithStackSkipWithExtrasAndContext

func (c *Client) ErrorWithStackSkipWithExtrasAndContext(ctx context.Context, level string, err error, skip int, extras map[string]interface{})

ErrorWithStackSkipWithExtrasAndContext sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped with extra custom data, within the given context.

func (*Client) Errorf

func (c *Client) Errorf(level string, format string, args ...interface{})

Errorf sends an error to Rollbar with the given format string and arguments.

func (*Client) Fingerprint

func (c *Client) Fingerprint() bool

Fingerprint specifies whether or not to use a custom client-side fingerprint.

func (*Client) LambdaWrapper

func (c *Client) LambdaWrapper(handlerFunc interface{}) interface{}

LambdaWrapper calls handlerFunc with arguments, and recovers and reports a panic to Rollbar if it occurs. This functions as a passthrough wrapper for lambda.Start(). This also waits before returning to ensure all messages completed.

func (*Client) LogPanic

func (c *Client) LogPanic(err interface{}, wait bool)

LogPanic accepts an error value returned by recover() and handles logging to Rollbar with stack info.

func (*Client) Message

func (c *Client) Message(level string, msg string)

Message sends a message to Rollbar with the given severity level.

func (*Client) MessageWithExtras

func (c *Client) MessageWithExtras(level string, msg string, extras map[string]interface{})

MessageWithExtras sends a message to Rollbar with the given severity level with extra custom data.

func (*Client) MessageWithExtrasAndContext

func (c *Client) MessageWithExtrasAndContext(ctx context.Context, level string, msg string, extras map[string]interface{})

MessageWithExtrasAndContext sends a message to Rollbar with the given severity level with extra custom data, within the given context.

func (*Client) Platform

func (c *Client) Platform() string

Platform is the currently set platform reported for all Rollbar items. The default is the running operating system (darwin, freebsd, linux, etc.) but it can also be application specific (client, heroku, etc.).

func (*Client) RequestError

func (c *Client) RequestError(level string, r *http.Request, err error)

RequestError sends an error to Rollbar with the given severity level and request-specific information.

func (*Client) RequestErrorWithExtras

func (c *Client) RequestErrorWithExtras(level string, r *http.Request, err error, extras map[string]interface{})

RequestErrorWithExtras sends an error to Rollbar with the given severity level and request-specific information with extra custom data.

func (*Client) RequestErrorWithExtrasAndContext

func (c *Client) RequestErrorWithExtrasAndContext(ctx context.Context, level string, r *http.Request, err error, extras map[string]interface{})

RequestErrorWithExtrasAndContext sends an error to Rollbar with the given severity level and request-specific information with extra custom data, within the given context.

func (*Client) RequestErrorWithStackSkip

func (c *Client) RequestErrorWithStackSkip(level string, r *http.Request, err error, skip int)

RequestErrorWithStackSkip sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped, in addition to extra request-specific information.

func (*Client) RequestErrorWithStackSkipWithExtras

func (c *Client) RequestErrorWithStackSkipWithExtras(level string, r *http.Request, err error, skip int, extras map[string]interface{})

RequestErrorWithStackSkipWithExtras sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped, in addition to extra request-specific information and extra custom data.

func (*Client) RequestErrorWithStackSkipWithExtrasAndContext

func (c *Client) RequestErrorWithStackSkipWithExtrasAndContext(ctx context.Context, level string, r *http.Request, err error, skip int, extras map[string]interface{})

RequestErrorWithStackSkipWithExtrasAndContext sends an error to Rollbar with the given severity level and a given number of stack trace frames skipped, in addition to extra request-specific information and extra custom data, within the given context.

func (*Client) RequestMessage

func (c *Client) RequestMessage(level string, r *http.Request, msg string)

RequestMessage sends a message to Rollbar with the given severity level and request-specific information.

func (*Client) RequestMessageWithExtras

func (c *Client) RequestMessageWithExtras(level string, r *http.Request, msg string, extras map[string]interface{})

RequestMessageWithExtras sends a message to Rollbar with the given severity level and request-specific information with extra custom data.

func (*Client) RequestMessageWithExtrasAndContext

func (c *Client) RequestMessageWithExtrasAndContext(ctx context.Context, level string, r *http.Request, msg string, extras map[string]interface{})

RequestMessageWithExtrasAndContext sends a message to Rollbar with the given severity level and request-specific information with extra custom data, within the given context.

func (*Client) ScrubFields

func (c *Client) ScrubFields() *regexp.Regexp

ScrubFields is the currently set regular expression to match keys in the item payload for scrubbing.

func (*Client) ScrubHeaders

func (c *Client) ScrubHeaders() *regexp.Regexp

ScrubHeaders is the currently set regular expression used to match headers for scrubbing.

func (*Client) ServerHost

func (c *Client) ServerHost() string

ServerHost is the currently set server hostname. This value will be indexed.

func (*Client) ServerRoot

func (c *Client) ServerRoot() string

ServerRoot is the currently set path to the application code root, not including the final slash. This is used to collapse non-project code when displaying tracebacks.

func (*Client) SetCaptureIp

func (c *Client) SetCaptureIp(captureIp captureIp)

SetCaptureIp sets what level of IP address information to capture from requests. CaptureIpFull means capture the entire address without any modification. CaptureIpAnonymize means apply a pseudo-anonymization. CaptureIpNone means do not capture anything.

func (*Client) SetCheckIgnore

func (c *Client) SetCheckIgnore(checkIgnore func(string) bool)

SetCheckIgnore sets the checkIgnore function which is called during the recovery process of a panic that occurred inside a function wrapped by Wrap or WrapAndWait. Return true if you wish to ignore this panic, false if you wish to report it to Rollbar. If an error is the argument to the panic, then this function is called with the result of calling Error(), otherwise the string representation of the value is passed to this function.

func (*Client) SetCodeVersion

func (c *Client) SetCodeVersion(codeVersion string)

SetCodeVersion sets the string describing the running code version on the server.

func (*Client) SetCustom

func (c *Client) SetCustom(custom map[string]interface{})

SetCustom sets any arbitrary metadata you want to send with every item.

func (*Client) SetEnabled

func (c *Client) SetEnabled(enabled bool)

SetEnabled sets whether or not Rollbar is enabled. If this is true then this library works as normal. If this is false then no calls will be made to the network. One place where this is useful is for turning off reporting in tests.

func (*Client) SetEndpoint

func (c *Client) SetEndpoint(endpoint string)

SetEndpoint sets the endpoint to post items to. This also configures the underlying Transport.

func (*Client) SetEnvironment

func (c *Client) SetEnvironment(environment string)

SetEnvironment sets the environment under which all errors and messages will be submitted.

func (*Client) SetFingerprint

func (c *Client) SetFingerprint(fingerprint bool)

SetFingerprint sets whether or not to use a custom client-side fingerprint. The default value is false.

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(httpClient *http.Client)

SetHTTPClient sets custom http client. http.DefaultClient is used by default

func (*Client) SetLogger

func (c *Client) SetLogger(logger ClientLogger)

SetLogger sets the logger on the underlying transport. By default log.Printf is used.

func (*Client) SetPerson

func (c *Client) SetPerson(id, username, email string)

SetPerson information for identifying a user associated with any subsequent errors or messages. Only id is required to be non-empty.

func (*Client) SetPlatform

func (c *Client) SetPlatform(platform string)

SetPlatform sets the platform to be reported for all items.

func (*Client) SetPrintPayloadOnError

func (c *Client) SetPrintPayloadOnError(printPayloadOnError bool)

SetPrintPayloadOnError sets whether or not to output the payload to the set logger or to stderr if an error occurs during transport to the Rollbar API. For example, if you hit your rate limit and we run out of retry attempts, then if this is true we will output the item to stderr rather than the item disappearing completely.

func (*Client) SetRetryAttempts

func (c *Client) SetRetryAttempts(retryAttempts int)

SetRetryAttempts sets how many times to attempt to retry sending an item if the http transport experiences temporary error conditions. By default this is equal to DefaultRetryAttempts. Temporary errors include timeouts and rate limit responses.

func (*Client) SetScrubFields

func (c *Client) SetScrubFields(fields *regexp.Regexp)

SetScrubFields sets the regular expression to match keys in the item payload for scrubbing. The default vlaue is regexp.MustCompile("password|secret|token"),

func (*Client) SetScrubHeaders

func (c *Client) SetScrubHeaders(headers *regexp.Regexp)

SetScrubHeaders sets the regular expression used to match headers for scrubbing. The default value is regexp.MustCompile("Authorization")

func (*Client) SetServerHost

func (c *Client) SetServerHost(serverHost string)

SetServerHost sets the hostname sent with each item. This value will be indexed.

func (*Client) SetServerRoot

func (c *Client) SetServerRoot(serverRoot string)

SetServerRoot sets the path to the application code root, not including the final slash. This is used to collapse non-project code when displaying tracebacks.

func (*Client) SetStackTracer

func (c *Client) SetStackTracer(stackTracer StackTracerFunc)

SetStackTracer sets the StackTracerFunc used by the client. The stack tracer function is used to extract the stack trace from enhanced error types. This feature can be used to add support for custom error types that do not implement the Stacker interface. See the documentation of StackTracerFunc for more details.

In order to preserve the default stack tracing behavior, callers of SetStackTracer may wish to include a call to DefaultStackTracer in their custom tracing function. See the example on the SetStackTracer function.

func (*Client) SetToken

func (c *Client) SetToken(token string)

SetToken sets the token used by this client. The value is a Rollbar access token with scope "post_server_item". It is required to set this value before any of the other functions herein will be able to work properly. This also configures the underlying Transport.

func (*Client) SetTransform

func (c *Client) SetTransform(transform func(map[string]interface{}))

SetTransform sets the transform function called after the entire payload has been built before it is sent to the API. The structure of the final payload sent to the API is:

{
    "access_token": "YOUR_ACCESS_TOKEN",
    "data": { ... }
}

This function takes a map[string]interface{} which is the value of the data key in the payload described above. You can modify this object in-place to make any arbitrary changes you wish to make before it is finally sent. Be careful with the modifications you make as they could lead to the payload being malformed from the perspective of the API.

func (*Client) SetUnwrapper

func (c *Client) SetUnwrapper(unwrapper UnwrapperFunc)

SetUnwrapper sets the UnwrapperFunc used by the client. The unwrapper function is used to extract wrapped errors from enhanced error types. This feature can be used to add support for custom error types that do not yet implement the Unwrap method specified in Go 1.13. See the documentation of UnwrapperFunc for more details.

In order to preserve the default unwrapping behavior, callers of SetUnwrapper may wish to include a call to DefaultUnwrapper in their custom unwrapper function. See the example on the SetUnwrapper function.

func (*Client) Token

func (c *Client) Token() string

Token is the currently set Rollbar access token.

func (*Client) Wait

func (c *Client) Wait()

Wait will call the Wait method of the Transport. If using an asynchronous transport then this will block until the queue of errors / messages is empty. If using a synchronous transport then there is no queue so this will be a no-op.

func (*Client) Wrap

func (c *Client) Wrap(f interface{}, args ...interface{}) (err interface{})

Wrap calls f and then recovers and reports a panic to Rollbar if it occurs. If an error is captured it is subsequently returned.

func (*Client) WrapAndWait

func (c *Client) WrapAndWait(f interface{}, args ...interface{}) (err interface{})

WrapAndWait calls f, and recovers and reports a panic to Rollbar if it occurs. This also waits before returning to ensure the message was reported If an error is captured it is subsequently returned.

func (*Client) WrapWithArgs

func (c *Client) WrapWithArgs(f interface{}, wait bool, inArgs ...interface{}) (err interface{})

WrapWithArgs calls f with the supplied args and reports a panic to Rollbar if it occurs. If wait is true, this also waits before returning to ensure the message was reported. If an error is captured it is subsequently returned. WrapWithArgs is compatible with any return type for f, but does not return its return value(s).

type ClientLogger

type ClientLogger interface {
	Printf(format string, args ...interface{})
}

ClientLogger is the interface used by the rollbar Client/Transport to report problems.

type ErrBufferFull

type ErrBufferFull struct{}

ErrBufferFull is an error which is returned when the asynchronous transport is used and the channel used for buffering items for sending to Rollbar is full.

func (ErrBufferFull) Error

func (e ErrBufferFull) Error() string

Error implements the error interface.

type ErrHTTPError

type ErrHTTPError int

ErrHTTPError is an HTTP error status code as defined by http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

func (ErrHTTPError) Error

func (e ErrHTTPError) Error() string

Error implements the error interface.

type Person

type Person struct {
	Id       string
	Username string
	Email    string
}

func PersonFromContext

func PersonFromContext(ctx context.Context) (*Person, bool)

PersonFromContext returns the Person value stored in ctx, if any.

type SilentClientLogger

type SilentClientLogger struct{}

SilentClientLogger is a type that implements the ClientLogger interface but produces no output.

func (*SilentClientLogger) Printf

func (s *SilentClientLogger) Printf(format string, args ...interface{})

Printf implements the ClientLogger interface.

type StackTracerFunc

type StackTracerFunc func(error) ([]runtime.Frame, bool)

A StackTracerFunc is used to extract stack traces when building an error chain. The first return value should be the extracted stack trace, if available. The second return value should be whether the function was able to extract a stack trace (even if the extracted stack trace was empty or nil).

The client will use DefaultStackTracer by default, and a user can override the default behavior by calling SetStackTracer. See SetStackTracer for more details.

var DefaultStackTracer StackTracerFunc = func(err error) ([]runtime.Frame, bool) {
	if s, ok := err.(Stacker); ok {
		return s.Stack(), true
	}

	return nil, false
}

DefaultStackTracer is the default StackTracerFunc used by rollbar-go clients. It can extract stack traces from error types implementing the Stacker interface (and by extension, the legacy CauseStacker interface).

To support stack trace extraction for other types of errors, see SetStackTracer.

type Stacker

type Stacker interface {
	Stack() []runtime.Frame
}

Stacker is an interface that errors can implement to allow the extraction of stack traces. To generate a stack trace, users are required to call runtime.Callers and build the runtime.Frame slice at the time the error is created.

type SyncTransport

type SyncTransport struct {
	// contains filtered or unexported fields
}

SyncTransport is a concrete implementation of the Transport type which communicates with the Rollbar API synchronously.

func NewSyncTransport

func NewSyncTransport(token, endpoint string) *SyncTransport

NewSyncTransport builds a synchronous transport which sends data to the Rollbar API at the specified endpoint using the given access token.

func (*SyncTransport) Close

func (t *SyncTransport) Close() error

Close is a no-op for the synchronous transport.

func (*SyncTransport) Send

func (t *SyncTransport) Send(body map[string]interface{}) error

Send the body to Rollbar. Returns errors associated with the http request if any. If the access token has not been set or is empty then this will not send anything and will return nil.

func (*SyncTransport) SetEndpoint

func (t *SyncTransport) SetEndpoint(endpoint string)

SetEndpoint updates the API endpoint to send items to.

func (*SyncTransport) SetHTTPClient

func (t *SyncTransport) SetHTTPClient(c *http.Client)

SetHTTPClient sets custom http client. http.DefaultClient is used by default

func (*SyncTransport) SetLogger

func (t *SyncTransport) SetLogger(logger ClientLogger)

SetLogger updates the logger that this transport uses for reporting errors that occur while processing items.

func (*SyncTransport) SetPrintPayloadOnError

func (t *SyncTransport) SetPrintPayloadOnError(printPayloadOnError bool)

SetPrintPayloadOnError is whether or not to output the payload to stderr if an error occurs during transport to the Rollbar API.

func (*SyncTransport) SetRetryAttempts

func (t *SyncTransport) SetRetryAttempts(retryAttempts int)

SetRetryAttempts is how often to attempt to resend an item when a temporary network error occurs This defaults to DefaultRetryAttempts Set this value to 0 if you do not want retries to happen

func (*SyncTransport) SetToken

func (t *SyncTransport) SetToken(token string)

SetToken updates the token to use for future API requests.

func (*SyncTransport) Wait

func (t *SyncTransport) Wait()

Wait is a no-op for the synchronous transport.

type Transport

type Transport interface {
	io.Closer
	// Send the body to the API, returning an error if the send fails. If the implementation to
	// asynchronous, then a failure can still occur when this method returns no error. In that case
	// this error represents a failure (or not) of enqueuing the payload.
	Send(body map[string]interface{}) error
	// Wait blocks until all messages currently waiting to be processed have been sent.
	Wait()
	// Set the access token to use for sending items with this transport.
	SetToken(token string)
	// Set the endpoint to send items to.
	SetEndpoint(endpoint string)
	// Set the logger to use instead of the standard log.Printf
	SetLogger(logger ClientLogger)
	// Set the number of times to retry sending an item if temporary http errors occurs before
	// failing.
	SetRetryAttempts(retryAttempts int)
	// Set whether to print the payload to the set logger or to stderr upon failing to send.
	SetPrintPayloadOnError(printPayloadOnError bool)
	// Sets custom http client. http.DefaultClient is used by default
	SetHTTPClient(httpClient *http.Client)
}

Transport represents an object used for communicating with the Rollbar API.

func NewTransport

func NewTransport(token, endpoint string) Transport

NewTransport creates a transport that sends items to the Rollbar API asynchronously.

type UnwrapperFunc

type UnwrapperFunc func(error) error

An UnwrapperFunc is used to extract wrapped errors when building an error chain. It should return the wrapped error if available, or nil otherwise.

The client will use DefaultUnwrapper by default, and a user can override the default behavior by calling SetUnwrapper. See SetUnwrapper for more details.

var DefaultUnwrapper UnwrapperFunc = func(err error) error {
	type causer interface {
		Cause() error
	}
	type wrapper interface {
		Unwrap() error
	}

	if e, ok := err.(causer); ok {
		return e.Cause()
	}
	if e, ok := err.(wrapper); ok {
		return e.Unwrap()
	}

	return nil
}

DefaultUnwrapper is the default UnwrapperFunc used by rollbar-go clients. It can unwrap any error types with the Unwrap method specified in Go 1.13, or any error type implementing the legacy CauseStacker interface.

It also implicitly supports errors from github.com/pkg/errors. However, users of pkg/errors may wish to also use the stack trace extraction features provided in the github.com/rollbar/rollbar-go/errors package.

Directories

Path Synopsis
errors module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto