rollbar-go: github.com/rollbar/rollbar-go Index | Examples | Files | Directories

package rollbar

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

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

Package Files

async_transport.go base_transport.go client.go doc.go errors.go rollbar.go stack.go sync_transport.go transforms.go transport.go

Constants

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
)
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]"
)
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
)

func CaptureIp Uses

func CaptureIp() captureIp

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

func ClearPerson Uses

func ClearPerson()

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

func Close Uses

func Close()

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

func CodeVersion Uses

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 Uses

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.

Code:

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

Code:

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

func Custom Uses

func Custom() map[string]interface{}

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

func Debug Uses

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.

Code:

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

Code:

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

func Endpoint Uses

func Endpoint() string

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

func Environment Uses

func Environment() string

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

func Error Uses

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.

Code:

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

Code:

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

func ErrorWithExtras Uses

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 Uses

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 Uses

func ErrorWithLevel(level string, err error)

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

func ErrorWithStackSkip Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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.

Code:

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

Code:

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

func LambdaWrapper Uses

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 Uses

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 Uses

func LogPanic(err interface{}, wait bool)

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

func Message Uses

func Message(level string, msg string)

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

func MessageWithExtras Uses

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 Uses

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 Uses

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

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

func Platform Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func ServerHost() string

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

func ServerRoot Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func SetHTTPClient(httpClient *http.Client)

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

func SetLogger Uses

func SetLogger(logger ClientLogger)

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

func SetPerson Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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.

Code:

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

func SetToken Uses

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 Uses

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 Uses

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.

Code:

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

func Token Uses

func Token() string

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

func Wait Uses

func Wait()

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

func Warning Uses

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.

Code:

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

Code:

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

func Wrap Uses

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 Uses

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 Uses

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

type AsyncTransport Uses

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 Uses

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 Uses

func (t *AsyncTransport) Close() error

Close is an alias for Wait for the asynchronous transport

func (*AsyncTransport) Send Uses

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 Uses

func (t *AsyncTransport) SetEndpoint(endpoint string)

SetEndpoint updates the API endpoint to send items to.

func (*AsyncTransport) SetHTTPClient Uses

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

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

func (*AsyncTransport) SetLogger Uses

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 Uses

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 Uses

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 Uses

func (t *AsyncTransport) SetToken(token string)

SetToken updates the token to use for future API requests.

func (*AsyncTransport) Wait Uses

func (t *AsyncTransport) Wait()

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

type CauseStacker Uses

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 Uses

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 Uses

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

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

func NewAsync Uses

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

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

func NewSync Uses

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

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

func (*Client) CaptureIp Uses

func (c *Client) CaptureIp() captureIp

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

func (*Client) ClearPerson Uses

func (c *Client) ClearPerson()

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

func (*Client) Close Uses

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 Uses

func (c *Client) CodeVersion() string

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

func (*Client) Custom Uses

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 Uses

func (c *Client) Endpoint() string

Endpoint is the currently set endpoint used for posting items.

func (*Client) Environment Uses

func (c *Client) Environment() string

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

func (*Client) ErrorWithExtras Uses

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 Uses

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 Uses

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

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

func (*Client) ErrorWithStackSkip Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (c *Client) Fingerprint() bool

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

func (*Client) LambdaWrapper Uses

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 Uses

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 Uses

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

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

func (*Client) MessageWithExtras Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

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

func (*Client) ServerHost Uses

func (c *Client) ServerHost() string

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

func (*Client) ServerRoot Uses

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 Uses

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 Uses

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 Uses

func (c *Client) SetCodeVersion(codeVersion string)

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

func (*Client) SetCustom Uses

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

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

func (*Client) SetEnabled Uses

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 Uses

func (c *Client) SetEndpoint(endpoint string)

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

func (*Client) SetEnvironment Uses

func (c *Client) SetEnvironment(environment string)

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

func (*Client) SetFingerprint Uses

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 Uses

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

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

func (*Client) SetLogger Uses

func (c *Client) SetLogger(logger ClientLogger)

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

func (*Client) SetPerson Uses

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 Uses

func (c *Client) SetPlatform(platform string)

SetPlatform sets the platform to be reported for all items.

func (*Client) SetPrintPayloadOnError Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (c *Client) SetServerHost(serverHost string)

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

func (*Client) SetServerRoot Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (c *Client) Token() string

Token is the currently set Rollbar access token.

func (*Client) Wait Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

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

type ErrBufferFull Uses

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 Uses

func (e ErrBufferFull) Error() string

Error implements the error interface.

type ErrHTTPError Uses

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 Uses

func (e ErrHTTPError) Error() string

Error implements the error interface.

type Person Uses

type Person struct {
    Id       string
    Username string
    Email    string
}

func PersonFromContext Uses

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

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

type SilentClientLogger Uses

type SilentClientLogger struct{}

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

func (*SilentClientLogger) Printf Uses

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

Printf implements the ClientLogger interface.

type StackTracerFunc Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (t *SyncTransport) Close() error

Close is a no-op for the synchronous transport.

func (*SyncTransport) Send Uses

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 Uses

func (t *SyncTransport) SetEndpoint(endpoint string)

SetEndpoint updates the API endpoint to send items to.

func (*SyncTransport) SetHTTPClient Uses

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

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

func (*SyncTransport) SetLogger Uses

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 Uses

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 Uses

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 Uses

func (t *SyncTransport) SetToken(token string)

SetToken updates the token to use for future API requests.

func (*SyncTransport) Wait Uses

func (t *SyncTransport) Wait()

Wait is a no-op for the synchronous transport.

type Transport Uses

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 Uses

func NewTransport(token, endpoint string) Transport

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

type UnwrapperFunc Uses

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

PathSynopsis
errors
example

Package rollbar imports 18 packages (graph) and is imported by 42 packages. Updated 2020-11-20. Refresh now. Tools for package owners.