rollbar

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2018 License: MIT Imports: 18 Imported by: 0

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

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("github.com/heroku/myproject") // 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
}

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.

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.

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 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() {
  panic(errors.New("AHHH!!!!"))
}

func main() {
  rollbar.SetToken("MY_TOKEN")
  err := rollbar.Wrap(PanickyFunction)
  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.

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 define the interface `CauseStacker`:

type CauseStacker interface {
  error
  Cause() error
  Stack() Stack
}

One can implement this interface for custom Error types to be able to build up a chain of stack traces. In order to get stack the correct stacks, callers must call BuildStack on their own at the time that the cause is wrapped. This is the least intrusive mechanism for gathering this information due to the decisions made by the Go runtime to not track this information.

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.0.1"

	// 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 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 added in v1.0.2

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 added in v1.0.2

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 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 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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.1

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 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 added in v1.0.1

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 added in v1.0.1

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 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 added in v1.0.1

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

Types

type AsyncTransport

type AsyncTransport struct {
	// Rollbar access token used by this transport for communication with the Rollbar API.
	Token string
	// Endpoint to post items to.
	Endpoint string
	// Logger used to report errors when sending data to Rollbar, e.g.
	// when the Rollbar API returns 409 Too Many Requests response.
	// If not set, the client will use the standard log.Printf by default.
	Logger ClientLogger
	// Buffer is the size of the channel used for queueing asynchronous payloads for sending to
	// Rollbar.
	Buffer int
	// RetryAttempts 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
	RetryAttempts int
	// PrintPayloadOnError is whether or not to output the payload to the set logger or to stderr
	// if an error occurs during transport to the Rollbar API.
	PrintPayloadOnError bool
	// 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. Any request that is currently in the queue will use this updated endpoint value. If you want to change the endpoint without affecting the items currently in the queue, use Wait first to flush the queue.

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 added in v1.0.1

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 added in v1.0.1

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. Any request that is currently in the queue will use this updated token value. If you want to change the token without affecting the items currently in the queue, use Wait first to flush the queue.

func (*AsyncTransport) Wait

func (t *AsyncTransport) Wait()

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

type CauseStacker

type CauseStacker interface {
	error
	Cause() error
	Stack() Stack
}

CauseStacker is an interface that errors can implement to create a trace_chain. Callers are required to call BuildStack on their own at the time the cause is wrapped.

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 added in v1.0.2

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 added in v1.0.2

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) 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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.2

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 added in v1.0.1

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) 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 added in v1.0.1

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 added in v1.0.1

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) 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 added in v1.0.1

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

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 Frame

type Frame struct {
	// Filename is the name of the file for this frame
	Filename string `json:"filename"`
	// Method is the name of the method for this frame
	Method string `json:"method"`
	// Line is the line number in the file for this frame
	Line int `json:"lineno"`
}

Frame represents one frame in a stack trace

type Person added in v1.0.2

type Person struct {
	Id       string
	Username string
	Email    string
}

func PersonFromContext added in v1.0.2

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 Stack

type Stack []Frame

A Stack is a slice of frames

func BuildStack

func BuildStack(skip int) Stack

BuildStack uses the Go runtime to construct a slice of frames optionally skipping the number of frames specified by the input skip argument.

func (Stack) Fingerprint

func (s Stack) Fingerprint() string

Fingerprint creates a fingerprint that uniqely identify a given message. We use the full callstack, including file names. That ensure that there are no false duplicates but also means that after changing the code (adding/removing lines), the fingerprints will change. It's a trade-off.

type SyncTransport

type SyncTransport struct {
	// Rollbar access token used by this transport for communication with the Rollbar API.
	Token string
	// Endpoint to post items to.
	Endpoint string
	// Logger used to report errors when sending data to Rollbar, e.g.
	// when the Rollbar API returns 409 Too Many Requests response.
	// If not set, the client will use the standard log.Printf by default.
	Logger ClientLogger
	// RetryAttempts 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
	RetryAttempts int
	// PrintPayloadOnError is whether or not to output the payload to the set logger or to stderr if
	// an error occurs during transport to the Rollbar API.
	PrintPayloadOnError bool
}

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) 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 added in v1.0.1

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 added in v1.0.1

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

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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