sentry

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2018 License: MIT Imports: 25 Imported by: 0

README

sentry-go Build Status codecov

A robust Sentry client for Go applications

This library is a re-imagining of how Go applications should interact with a Sentry server. It aims to offer a concise, easy to understand and easy to extend toolkit for sending events to Sentry, with a strong emphasis on being easy to use.

Features

  • A beautiful API which makes it obvious exactly what the best way to solve a problem is.
  • Comprehensive coverage of the various objects that can be sent to Sentry so you won't be left wondering why everyone else gets to play with Breadcrumbs but you still can't...
  • StackTrace Support using the official pkg/errors stacktrace provider, for maximum compatibility and easy integration with other libraries.
  • HTTP Context Helpers to let you quickly expose HTTP request context as part of your errors - with optional support for sending cookies, headers and payload data.
  • Extensive documentation which makes figuring out the right way to use something as easy as possible without the need to go diving into the code.

In addition to the features listed above, the library offers support for a number of more advanced use cases, including sending events to multiple different Sentry DSNs, derived client contexts, custom interface types and custom transports.

Versions

This package follows SemVer and uses gopkg.in to provide access to those versions.

  • sentry-go.v0 - import ("gopkg.in/SierraSoftworks/sentry-go.v0")

    This version is the latest master branch. You should avoid depending on this version unless you are performing active development against sentry-go.

  • sentry-go.v1 - import ("gopkg.in/SierraSoftworks/sentry-go.v1")

    This version is the most recent release of sentry-go and will maintain API compatibility. If you are creating a project that relies on sentry-go then this is the version you should use.

Examples

Breadcrumbs and Exceptions
package main

import (
    "fmt"

    "gopkg.in/SierraSoftworks/sentry-go.v1"
    "github.com/pkg/errors"
)

func main() {
    sentry.AddDefaultOptions(
        sentry.DSN("..."), // If you don't override this, it'll be fetched from $SENTRY_DSN
        sentry.Release("v1.0.0"),
    )

    cl := sentry.NewClient()

    sentry.DefaultBreadcrumbs().NewDefault(nil).WithMessage("Application started").WithCategory("log")

    err := errors.New("error with a stacktrace")

    id := cl.Capture(
        sentry.Message("Example exception submission to Sentry"),
        sentry.ExceptionForError(err),
    ).Wait().EventID()
    fmt.Println("Sent event to Sentry: ", id)
}
HTTP Request Context
package main

import (
    "net/http"
    "os"
    
    "gopkg.in/SierraSoftworks/sentry-go.v1"
)

func main() {
    cl := sentry.NewClient(
        sentry.Release("v1.0.0"),
    )

    http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
        cl := cl.With(
            sentry.HTTPRequest(req).WithHeaders(),
        )

        res.Header().Set("Content-Type", "application/json")
        res.WriteHeader(404)
        res.Write([]byte(`{"error":"Not Found","message":"We could not find the route you requested, please check your URL and try again."}`))

        cl.Capture(
            sentry.Message("Route Not Found: [%s] %s", req.Method, req.URL.Path),
            sentry.Level(sentry.Warning),
        )
    })

    if err := http.ListenAndServe(":8080", nil); err != nil {
        cl.Capture(
            sentry.ExceptionForError(err),
            sentry.Level(sentry.Fatal),
            sentry.Extra(map[string]interface{}{
                "port": 8080,
            }),
        )

        os.Exit(1)
    }
}

Advanced Use Cases

Custom SendQueues

The default send queue provided by this library is a serial, buffered, queue which waits for a request to complete before sending the next. This works well to limit the potential for clients DoSing your Sentry server, but might not be what you want.

For situations where you'd prefer to use a different type of queue algorithm, this library allows you to change the queue implementation both globally and on a per-client basis. You may also opt to use multiple send queues spread between different clients to impose custom behaviour for different portions of your application.

import "gopkg.in/SierraSoftworks/sentry-go.v1"

func main() {
    // Configure a new global send queue
    sentry.AddDefaultOptions(
        sentry.UseSendQueue(sentry.NewSequentialSendQueue(10)),
    )

    cl := sentry.NewClient()
    cl.Capture(sentry.Message("Sent over the global queue"))

    // Create a client with its own send queue
    cl2 := sentry.NewClient(
        UseSendQueue(sentry.NewSequentialSendQueue(100)),
    )
    cl2.Capture(sentry.Message("Sent over the client's queue"))
}

SendQueue implementations must implement the SendQueue interface, which requires it to provide both the Enqueue and Shutdown methods.

Documentation

Overview

The sentry package gives you the ability to send events to a Sentry server. It provides a clean API with comprehensive support for Sentry's various interfaces and an easy to remember syntax.

Example
cl := NewClient(
	// Your DSN is fetched from the $SENTRY_DSN environment
	// variable automatically. But you can override it if you
	// prefer...
	DSN("https://key:secret@example.com/sentry/1"),
	Release("v1.0.0"),

	// Your environment is fetched from $ENV/$ENVIRONMENT automatically,
	// but you can override it here if you prefer.
	Environment("example"),

	Logger("example"),
)

err := errors.New("something went wrong")

// The HTTP request that was being handled when this error occurred
var req *http.Request

e := cl.Capture(
	Culprit("GET /api/v1/explode"),
	ExceptionForError(err),
	HTTPRequest(req).WithHeaders().WithCookies(),
)

if err := e.Error(); err != nil {
	fmt.Printf("Failed to send event: %s", err.Error())
} else {
	fmt.Printf("Sent event (id: %s)\n", e.EventID())
}
Output:

Index

Examples

Constants

View Source
const (
	// ErrBadURL is returned when a DSN cannot be parsed due to
	// formatting errors in its URL
	ErrBadURL = ErrType("sentry: bad DSN URL")

	// ErrMissingPublicKey is returned when a DSN does not have
	// a valid public key contained within its URL
	ErrMissingPublicKey = ErrType("sentry: missing public key")

	// ErrMissingPrivateKey is returned when a DSN does not have
	// a valid private key contained within its URL
	ErrMissingPrivateKey = ErrType("sentry: missing private key")

	// ErrMissingProjectID is returned when a DSN does not have a valid
	// project ID contained within its URL
	ErrMissingProjectID = ErrType("sentry: missing project ID")
)
View Source
const (
	// ErrSendQueueFull is used when an attempt to enqueue a
	// new event fails as a result of no buffer space being available.
	ErrSendQueueFull = ErrType("sentry: send queue was full")

	// ErrSendQueueShutdown is used when an attempt to enqueue
	// a new event fails as a result of the queue having been shutdown
	// already.
	ErrSendQueueShutdown = ErrType("sentry: send queue was shutdown")
)
View Source
const (
	// Fatal represents exceptions which result in the application exiting fatally
	Fatal = Severity("fatal")

	// Error represents exceptions which break the expected application flow
	Error = Severity("error")

	// Warning represents events which are abnormal but do not prevent the application
	// from operating correctly
	Warning = Severity("warning")

	// Info is used to expose information about events which occur during normal
	// operation of the application
	Info = Severity("info")

	// Debug is used to expose verbose information about events which occur during
	// normal operation of the application
	Debug = Severity("debug")
)
View Source
const (
	// ErrMissingRootTLSCerts is used when this library cannot load the required
	// RootCA certificates needed for its HTTPS transport.
	ErrMissingRootTLSCerts = ErrType("sentry: Failed to load root TLS certificates")
)

Variables

This section is empty.

Functions

func AddDefaultOptionProvider

func AddDefaultOptionProvider(provider func() Option)

AddDefaultOptionProvider allows you to register a new default option which will be globally set on all top-level clients. You can override this option later by specifying a replacement in each client or event's options list.

Example
// You can also register options providers which will dynamically
// generate options for each new event that is sent
AddDefaultOptionProvider(func() Option {
	if dsn := os.Getenv("SENTRY_DSN"); dsn != "" {
		return DSN(dsn)
	}

	return nil
})
Output:

func AddDefaultOptions

func AddDefaultOptions(options ...Option)

AddDefaultOptions allows you to configure options which will be globally set on all top-level clients by default. You can override these options later by specifying replacements in each client or event's options list.

Example
// You can add default options to all of your root Sentry
// clients like this.
AddDefaultOptions(
	Release("v1.0.0"),
	DSN("..."),
)
Output:

func AddInternalPrefixes

func AddInternalPrefixes(prefixes ...string)

AddInternalPrefixes allows you to easily add packages which will be considered "internal" in your stack traces.

Example
// This adds the provided prefixes to your list of internal
// package prefixes used to tag stacktrace frames as in-app.
AddInternalPrefixes("github.com/SierraSoftworks/sentry-go")
Output:

func NewEventID

func NewEventID() (string, error)

NewEventID attempts to generate a new random UUIDv4 event ID which can be passed to the EventID() option.

Types

type Breadcrumb interface {
	// WithMessage sets the message displayed for this breadcrumb
	WithMessage(msg string) Breadcrumb

	// WithCategory sets the category that this breadcrumb belongs to
	WithCategory(cat string) Breadcrumb

	// Level sets the severity level of this breadcrumb to one of the
	// predefined severity levels.
	WithLevel(s Severity) Breadcrumb

	// WithTimestamp overrides the timestamp of this breadcrumb with
	// a new one.
	WithTimestamp(ts time.Time) Breadcrumb
}

A Breadcrumb keeps track of an action which took place in the application leading up to an event.

Example
b := DefaultBreadcrumbs().NewDefault(nil)

// You can set the severity level for the breadcrumb
b.WithLevel(Error)

// You can configure the category that the breadcrumb belongs to
b.WithCategory("auth")

// You can also specify a message describing the breadcrumb
b.WithMessage("User's credentials were invalid")

// And if you need to change the timestamp, you can do that too
b.WithTimestamp(time.Now())

// All together now!
DefaultBreadcrumbs().
	NewDefault(nil).
	WithLevel(Error).
	WithCategory("auth").
	WithMessage("User's credentials were invalid").
	WithTimestamp(time.Now())
Output:

type BreadcrumbsList interface {
	// Adjusts the maximum number of breadcrumbs which will be maintained
	// in this list.
	WithSize(length int) BreadcrumbsList

	// NewDefault creates a new breadcrumb using the `default` type.
	// You can provide any data you wish to include in the breadcrumb,
	// or nil if you do not wish to include any extra data.
	NewDefault(data map[string]interface{}) Breadcrumb

	// NewNavigation creates a new navigation breadcrumb which represents
	// a transition from one page to another.
	NewNavigation(from, to string) Breadcrumb

	// NewHTTPRequest creates a new HTTP request breadcrumb which
	// describes the results of an HTTP request.
	NewHTTPRequest(method, url string, statusCode int, reason string) Breadcrumb
}

A BreadcrumbsList is responsible for keeping track of all the breadcrumbs that make up a sequence. It will automatically remove old breadcrumbs as new ones are added and is both type-safe and O(1) execution time for inserts and removals.

func DefaultBreadcrumbs

func DefaultBreadcrumbs() BreadcrumbsList

DefaultBreadcrumbs are registered for inclusion in situations where you have not specified your own Breadcrumbs collection. You can use them to keep track of global events throughout your application.

Example
// We can change the maximum number of breadcrumbs to be stored
DefaultBreadcrumbs().WithSize(5)

DefaultBreadcrumbs().NewDefault(nil).WithMessage("This is an example")
DefaultBreadcrumbs().NewDefault(map[string]interface{}{
	"example": true,
}).WithMessage("It should give you an idea of how you can use breadcrumbs in your app")

DefaultBreadcrumbs().
	NewNavigation("introduction", "navigation").
	WithCategory("navigation").
	WithMessage("You can use them to represent navigations from one page to another")

DefaultBreadcrumbs().
	NewNavigation("navigation", "http").
	WithCategory("navigation").
	WithMessage("Or to represent changes in the state of your application's workflows")

DefaultBreadcrumbs().
	NewHTTPRequest("GET", "https://example.com/api/v1/awesome", 200, "OK").
	WithLevel(Debug).
	WithMessage("I think we can agree that they're pretty awesome")

NewClient().Capture(Message("Finally, we send the event with all our breadcrumbs included"))
Output:

func NewBreadcrumbsList

func NewBreadcrumbsList(size int) BreadcrumbsList

NewBreadcrumbsList will create a new BreadcrumbsList which can be used to track breadcrumbs within a specific context.

type Client

type Client interface {
	// With creates a new derivative client with the provided options
	// set as part of its defaults.
	With(options ...Option) Client

	// GetOption allows you to retrieve a specific configuration object
	// by its Class name from this client. It is useful if you are interested
	// in using the client to configure Sentry plugins.
	// If an option with the given className could not be found, nil will
	// be returned.
	GetOption(className string) Option

	// Capture will queue an event for sending to Sentry and return a
	// QueuedEvent object which can be used to keep tabs on when it is
	// actually sent, if you are curious.
	Capture(options ...Option) QueuedEvent
}

A Client is responsible for letting you interact with the Sentry API. You can create derivative clients

Example
// You can create a new root client directly and configure
// it by passing any options you wish
cl := NewClient(
	DSN(""),
)

// You can then create a derivative client with any context-specific
// options. These are useful if you want to encapsulate context-specific
// information like the HTTP request that is being handled.
var r *http.Request
ctxCl := cl.With(
	HTTPRequest(r).WithHeaders(),
	Logger("http"),
)

// You can then use the client to capture an event and send it to Sentry
err := fmt.Errorf("an error occurred")
ctxCl.Capture(
	ExceptionForError(err),
)
Output:

func DefaultClient

func DefaultClient() Client

DefaultClient is a singleton client instance which can be used instead of instantiating a new client manually.

Example
DefaultClient().Capture(
	Message("This is an example message"),
)
Output:

func NewClient

func NewClient(options ...Option) Client

NewClient will create a new client instance with the provided default options and config.

type Config

type Config interface {
	DSN() string
	Transport() Transport
	SendQueue() SendQueue
}

A Config allows you to control how events are sent to Sentry. It is usually populated through the standard build pipeline through the DSN() and UseTransport() options.

type DeviceContextInfo

type DeviceContextInfo struct {
	Type         string `json:"type,omitempty"`
	Name         string `json:"name"`
	Family       string `json:"family,omitempty"`
	Model        string `json:"model,omitempty"`
	ModelID      string `json:"model_id,omitempty"`
	Architecture string `json:"arch,omitempty"`
	BatteryLevel int    `json:"battery_level,omitempty"`
	Orientation  string `json:"orientation,omitempty"`
}

DeviceContextInfo describes the device that your application is running on.

type ErrType

type ErrType string

func (ErrType) Error

func (e ErrType) Error() string

Error gets the error message for this ErrType

func (ErrType) IsInstance

func (e ErrType) IsInstance(err error) bool

IsInstance will tell you whether a given error is an instance of this ErrType

type ExceptionInfo

type ExceptionInfo struct {
	Type       string           `json:"type"`
	Value      string           `json:"value"`
	Module     string           `json:"module,omitempty"`
	ThreadID   string           `json:"thread_id,omitempty"`
	Mechanism  string           `json:"mechanism,omitempty"`
	StackTrace StackTraceOption `json:"stacktrace,omitempty"`
}

An ExceptionInfo describes the details of an exception that occurred within your application.

func NewExceptionInfo

func NewExceptionInfo() *ExceptionInfo

NewExceptionInfo creates a new ExceptionInfo object which can then be populated with information about an exception which occurred before being passed to the Exception() method for submission to Sentry.

func (*ExceptionInfo) ForError

func (e *ExceptionInfo) ForError(err error) *ExceptionInfo

ForError updates an ExceptionInfo object with information sourced from an error.

type FinalizableOption

type FinalizableOption interface {
	Finalize()
}

A FinalizableOption exposes a Finalize() method which is called by the Packet builder before its value is used. This gives the option the opportunity to perform any last-minute formatting and configuration.

type HTTPRequestInfo

type HTTPRequestInfo struct {
	URL    string `json:"url"`
	Method string `json:"method"`
	Query  string `json:"query_string,omitempty"`

	// These fields are optional
	Cookies string            `json:"cookies,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
	Data    interface{}       `json:"data,omitempty"`
}

HTTPRequestInfo is a low-level interface which describes the details of an HTTP request made to a web server. If you are using the net/http library, the HTTPRequest() option will populate this information for you automatically.

func (*HTTPRequestInfo) Class

func (o *HTTPRequestInfo) Class() string

Class is used to meet the Option interface constraints by providing the name of the API field that this data will be submitted in.

type HTTPRequestOption

type HTTPRequestOption interface {
	Option
	WithCookies() HTTPRequestOption
	WithHeaders() HTTPRequestOption
	WithEnv() HTTPRequestOption
	WithData(data interface{}) HTTPRequestOption
	Sanitize(fields ...string) HTTPRequestOption
}

An HTTPRequestOption describes an HTTP request's data

func HTTPRequest

func HTTPRequest(req *http.Request) HTTPRequestOption

HTTPRequest passes the request context from a net/http request object to Sentry. It exposes a number of options to control what information is exposed and how it is sanitized.

Example
cl := NewClient(
	Release("v1.0.0"),
)

// Add your 404 handler to the default mux
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
	cl := cl.With(
		// Set the HTTP request context for your request's client
		HTTPRequest(req).WithHeaders(),
	)

	res.Header().Set("Content-Type", "application/json")
	res.WriteHeader(404)
	res.Write([]byte(`{"error":"Not Found","message":"We could not find the route you requested, please check your URL and try again."}`))

	// Capture the problem using your request's client
	cl.Capture(
		Message("Route Not Found: [%s] %s", req.Method, req.URL.Path),
		Level(Warning),
	)
})
Output:

type MergeableOption

type MergeableOption interface {
	Merge(old Option) Option
}

The MergeableOption interface gives options the ability to merge themselves with other instances posessing the same class name. Sometimes it makes sense to offer the ability to merge multiple options of the same type together before they are rendered. This interface gives options the ability to define how that merging should occur.

type OSContextInfo

type OSContextInfo struct {
	Type          string `json:"type,omitempty"`
	Name          string `json:"name"`
	Version       string `json:"version,omitempty"`
	Build         string `json:"build,omitempty"`
	KernelVersion string `json:"kernel_version,omitempty"`
	Rooted        bool   `json:"rooted,omitempty"`
}

OSContextInfo describes the operating system that your application is running on.

type OmitableOption

type OmitableOption interface {
	Omit() bool
}

An OmitableOption can opt to have itself left out of the packet by making an addition-time determination in its Omit() function. This is a useful tool for excluding empty fields automatically.

type Option

type Option interface {
	Class() string
}

An Option represents an object which can be written to the Sentry packet as a field with a given class name. Options may implement additional interfaces to control how their values are rendered or to offer the ability to merge multiple instances together.

func Breadcrumbs(list BreadcrumbsList) Option

Breadcrumbs can be included in your events to help track down the sequence of steps that resulted in a failure.

Example
rootClient := NewClient()
DefaultBreadcrumbs().NewDefault(nil).WithMessage("Breadcrumb in the default context")

breadcrumbs := NewBreadcrumbsList(10)
contextClient := rootClient.With(Breadcrumbs(breadcrumbs))
breadcrumbs.NewDefault(nil).WithMessage("Breadcrumb in the private context")

// Will include only the first breadcrumb
rootClient.Capture(
	Message("Event in default context"),
	Logger("default"),
)

// Will include only the second breadcrumb
contextClient.Capture(
	Message("Event in private context"),
	Logger("private"),
)
Output:

func Context

func Context(key string, data interface{}) Option

Context allows you to manually set a context entry by providing its key and the data to accompany it. This is a low-level method and you should be familiar with the correct usage of contexts before using it. https://docs.sentry.io/clientdev/interfaces/contexts/

func Culprit

func Culprit(culprit string) Option

Culprit allows you to specify the name of the transaction (or culprit) which casued this event. For example, in a web app, this might be the route name: `/welcome/`

Example
cl := NewClient(
	// You can set this when creating your client
	Culprit("example"),
)

cl.Capture(
	// Or you can set it when sending an event
	Culprit("example"),
)
Output:

func DSN

func DSN(dsn string) Option

DSN lets you specify the unique Sentry DSN used to submit events for your application. Specifying an empty DSN will disable the client.

Example
cl := NewClient(
	// You can configure the DSN when creating a client
	DSN("https://key:pass@example.com/sentry/1"),
)

cl.Capture(
	// You can also configure the DSN when sending an event
	DSN(""),
	Message("This won't be sent"),
)
Output:

func DeviceContext

func DeviceContext(info *DeviceContextInfo) Option

DeviceContext allows you to set the context describing the device that your application is being executed on.

Example
deviceInfo := DeviceContextInfo{
	Architecture: "arm",
	BatteryLevel: 100,
	Family:       "Samsung Galaxy",
	Model:        "Samsung Galaxy S8",
	ModelID:      "SM-G95550",
	Name:         "Samsung Galaxy S8",
	Orientation:  "portrait",
}

cl := NewClient(
	// You can provide this when creating your client
	DeviceContext(&deviceInfo),
)

cl.Capture(
	// Or when you send an event
	DeviceContext(&deviceInfo),
)
Output:

func Environment

func Environment(env string) Option

Environment allows you to configure the name of the environment you pass to Sentry with your event. This would usually be something like "production" or "staging".

Example
cl := NewClient(
	// You can configure your environment at the client level
	Environment("development"),
)

cl.Capture(
	// ...or at the event level
	Environment("prod"),
)
Output:

func EventID

func EventID(id string) Option

EventID is an option which controls the UUID used to represent an event. The ID should be exactly 32 hexadecimal characters long and include no dashes. If an invalid ID is passed to this option, it will return nil and be ignored by the packet builder.

Example
id, err := NewEventID()
if err != nil {
	log.Fatalln(err)
}

cl := NewClient()

ctxCl := cl.With(
	// You could set the event ID for a context specific
	// client if you wanted (but you probably shouldn't).
	EventID(id),
)

ctxCl.Capture(
	// The best place to set it is when you are ready to send
	// an event to Sentry.
	EventID(id),
)
Output:

func Exception

func Exception(info *ExceptionInfo) Option

Exception allows you to include the details of an exception which occurred within your application as part of the event you send to Sentry.

func ExceptionForError

func ExceptionForError(err error) Option

ExceptionForError allows you to include the details of an error which occurred within your application as part of the event you send to Sentry.

func Extra

func Extra(extra map[string]interface{}) Option

Extra allows you to provide additional arbitrary metadata with your event. This data is not searchable, but can be invaluable in identifying the cause of a problem.

Example
cl := NewClient(
	// You can define extra fields when you create your client
	Extra(map[string]interface{}{
		"redis": map[string]interface{}{
			"host": "redis",
			"port": 6379,
		},
	}),
)

cl.Capture(
	// You can also define extra info when you send the event
	// The extra object will be shallowly merged automatically,
	// so this would send both `redis` and `cache`.
	Extra(map[string]interface{}{
		"cache": map[string]interface{}{
			"key": "user.127.profile",
			"hit": false,
		},
	}),
)
Output:

func Fingerprint

func Fingerprint(keys ...string) Option

Fingerprint is used to configure the array of strings used to deduplicate events when they are processed by Sentry. You may use the special value "{{ default }}" to extend the default behaviour if you wish. https://docs.sentry.io/learn/rollups/#custom-grouping

Example
cl := NewClient()

cl.Capture(
	// You can specify a fingerprint that extends the default behaviour
	Fingerprint("{{ default }}", "http://example.com/my.url"),

	// Or you can define your own
	Fingerprint("myrpc", "POST", "/foo.bar"),
)
Output:

func HTTP

func HTTP(h *HTTPRequestInfo) Option

HTTP creates a new HTTP interface with the raw data provided by a user. It is useful in situations where you are not leveraging Go's underlying net/http library or wish to have direct control over the values sent to Sentry. For all other purposes, the HTTPRequest() option is a more useful replacement.

Example
// You can manually populate all this request info in situations
// where you aren't using `net/http` as your HTTP server (or don't
// have access to the http.Request object).
// In all other situations, you're better off using `HTTPRequest(r)`
// and saving yourself the effort of building this up manually.
ri := &HTTPRequestInfo{
	URL:    "http://example.com/my.url",
	Method: "GET",
	Query:  "q=test",

	Cookies: "testing=1",
	Headers: map[string]string{
		"Host": "example.com",
	},
	Env: map[string]string{
		"REMOTE_ADDR": "127.0.0.1",
		"REMOTE_PORT": "18204",
	},
	Data: map[string]interface{}{
		"awesome": true,
	},
}

cl := NewClient()

ctxCl := cl.With(
	// You can provide the HTTP request context in a context-specific
	// derived client
	HTTP(ri),
)

ctxCl.Capture(
	// Or you can provide it when sending an event
	HTTP(ri),
)
Output:

func Level

func Level(severity Severity) Option

Level is used to set the severity level of an event before it is sent to Sentry

Example
cl := NewClient(
	// You can set the severity level when you create your client
	Level(Debug),
)

cl.Capture(
	// You can also specify it when sending an event
	Level(Error),
)
Output:

func Logger

func Logger(logger string) Option

Logger allows you to configure the hostname reported to Sentry with an event.

Example
cl := NewClient(
	// You can set the logger when you create your client
	Logger("root"),
)

cl.Capture(
	// You can also specify it when sending an event
	Logger("http"),
)
Output:

func Message

func Message(format string, params ...interface{}) Option

Message generates a new message entry for Sentry, optionally using a format string with standard fmt.Sprintf params.

Example
cl := NewClient()

cl.Capture(
	// You can either use just a simple message
	Message("this is a simple message"),
)

cl.Capture(
	// Or you can provide formatting entries as you would with
	// fmt.Sprintf() calls.
	Message("this is a %s message (%d/7 would use again)", "formatted", 5),
)
Output:

func Modules

func Modules(moduleVersions map[string]string) Option

Modules allows you to specify the versions of various modules used by your application.

Example
cl := NewClient(
	// You can specify module versions when creating your
	// client
	Modules(map[string]string{
		"redis": "v1",
		"mgo":   "v2",
	}),
)

cl.Capture(
	// And override or expand on them when sending an event
	Modules(map[string]string{
		"redis":     "v2",
		"sentry-go": "v1",
	}),
)
Output:

func OSContext

func OSContext(info *OSContextInfo) Option

OSContext allows you to set the context describing the operating system that your application is running on.

Example
osInfo := OSContextInfo{
	Version:       "CentOS 7.3",
	Build:         "centos7.3.1611",
	KernelVersion: "3.10.0-514",
	Rooted:        false,
}

cl := NewClient(
	// You can provide this when creating your client
	OSContext(&osInfo),
)

cl.Capture(
	// Or when you send an event
	OSContext(&osInfo),
)
Output:

func Platform

func Platform(platform string) Option

Platform allows you to configure the platform reported to Sentry. This is used to customizae portions of the user interface.

Example
cl := NewClient(
	// You can set the platform at a client level
	Platform("go"),
)

cl.Capture(
	// Or override it when sending the event
	Platform("go"),
)
Output:

func Release

func Release(version string) Option

Release allows you to configure the application release version reported to Sentry with an event.

Example
cl := NewClient(
	// You can set the release when you create a client
	Release("v1.0.0"),
)

cl.Capture(
	// You can also set it when you send an event
	Release("v1.0.0-dev"),
)
Output:

func RuntimeContext

func RuntimeContext(name, version string) Option

RuntimeContext allows you to set the information pertaining to the runtime that your program is executing on.

Example
cl := NewClient(
	// You can configure this when creating your client
	RuntimeContext("go", runtime.Version()),
)

cl.Capture(
	// Or when sending an event
	RuntimeContext("go", runtime.Version()),
)
Output:

func ServerName

func ServerName(hostname string) Option

ServerName allows you to configure the hostname reported to Sentry with an event.

Example
cl := NewClient(
	// You can set the logger when you create your client
	ServerName("web01"),
)

cl.Capture(
	// You can also specify it when sending an event
	ServerName("web01.prod"),
)
Output:

func Tags

func Tags(tags map[string]string) Option

Tags allow you to add additional tagging information to events which makes it possible to easily group and query similar events.

Example
cl := NewClient(
	// You can specify tags when creating your client
	Tags(map[string]string{
		"redis": "v1",
		"mgo":   "v2",
	}),
)

cl.Capture(
	// And override or expand on them when sending an event
	Tags(map[string]string{
		"redis":     "v2",
		"sentry-go": "v1",
	}),
)
Output:

func Timestamp

func Timestamp(timestamp time.Time) Option

Timestamp allows you to provide a custom timestamp for an event that is sent to Sentry.

Example
cl := NewClient()

cl.Capture(
	// You can specify the timestamp when sending an event to Sentry
	Timestamp(time.Now()),
)
Output:

func UseSendQueue

func UseSendQueue(queue SendQueue) Option

UseSendQueue allows you to specify the send queue that will be used by a client.

Example
cl := NewClient(
	// You can override the send queue on your root client
	// All of its derived clients will inherit this queue
	UseSendQueue(NewSequentialSendQueue(10)),
)

cl.With(
	// Or you can override it on a derived client
	UseSendQueue(NewSequentialSendQueue(10)),
)
Output:

func UseTransport

func UseTransport(transport Transport) Option

UseTransport allows you to control which transport is used to send events for a specific client or packet.

Example
var myTransport Transport

cl := NewClient(
	// You can configure the transport to be used on a client level
	UseTransport(myTransport),
)

cl.Capture(
	// Or for a specific event when it is sent
	UseTransport(myTransport),
)
Output:

func User

func User(user *UserInfo) Option

User allows you to include the details of a user that was interacting with your application when the error occurred.

Example
user := UserInfo{
	ID:        "17ba08f7cc89a912bf812918",
	Email:     "test@example.com",
	Username:  "Test User",
	IPAddress: "127.0.0.1",
	Extra: map[string]string{
		"role": "Tester",
	},
}

cl := NewClient(
	// You can specify your user when you create your client
	User(&user),
)

cl.Capture(
	// Or when you send an event to Sentry
	User(&user),
)
Output:

type Packet

type Packet interface {
	// SetOptions will set all non-nil options provided, intelligently
	// merging values when supported by an option, or replacing existing
	// values if not.
	SetOptions(options ...Option) Packet

	// Clone will create a copy of this packet which can then be modified
	// independently. In most cases it is a better idea to create a new
	// client with the options you wish to override, however there are
	// situations where this is a cleaner solution.
	Clone() Packet
}

A Packet is a JSON serializable object that will be sent to the Sentry server to describe an event. It provides convinience methods for setting options and handling the various types of option that can be added.

Example
// Create a new packet object which can be sent to
// Sentry by one of the transports or send queues.
p := NewPacket().SetOptions(
	DSN(""),
	Message("Custom packet creation"),
)

// Create a clone of this packet if you want to use
// it as a template
p.Clone().SetOptions(
	Message("Overridden message which doesn't affect the original"),
)
Output:

func NewPacket

func NewPacket() Packet

NewPacket creates a new packet which will be sent to the Sentry server after its various options have been set. You will not usually need to create a Packet yourself, instead you should use your `Client`'s `Capture()` method.

type QueuedEvent

type QueuedEvent interface {
	EventID() string
	Wait() QueuedEvent
	WaitChannel() <-chan error
	Error() error
}

A QueuedEvent allows you to track the status of sending an event to Sentry.

Example
cl := NewClient()

e := cl.Capture(
	Message("Example Event"),
)

// You can then wait on the event to be sent
e.Wait()

// Or you can use the WaitChannel if you want support for timeouts
select {
case err := <-e.WaitChannel():
	if err != nil {
		fmt.Println("failed to send event: ", err)
	} else {
		// You can also get the EventID for this event
		fmt.Println("sent event: ", e.EventID())
	}
case <-time.After(time.Second):
	fmt.Println("timed out waiting for send")
}
Output:

func NewQueuedEvent

func NewQueuedEvent(cfg Config, packet Packet) QueuedEvent

NewQueuedEvent is used by SendQueue implementations to expose information about the events that they are sending to Sentry.

type QueuedEventInternal

type QueuedEventInternal interface {
	QueuedEvent
	Packet() Packet
	Config() Config
	Complete(err error)
}

QueuedEventInternal is an interface used by SendQueue implementations to "complete" a queued event once it has either been sent to Sentry, or sending failed with an error.

Example
// If you're implementing your own send queue, you will want to use
// the QueuedEventInternal to control when events are finished and
// to access the packet and config related to them.

cl := NewClient()
e := cl.Capture()

if ei, ok := e.(QueuedEventInternal); ok {
	// Get the packet for the event
	p := ei.Packet()

	// Get the config for the event
	cfg := ei.Config()

	// Use the configured transport to send the packet
	err := cfg.Transport().Send(cfg.DSN(), p)

	// Complete the event (with the error, if not nil)
	ei.Complete(err)
}
Output:

type SendQueue

type SendQueue interface {
	// Enqueue is called by clients wishing to send an event to Sentry.
	// It is provided with a Config and Packet and is expected to return
	// a QueuedEvent compatible object which an application can use to
	// access information about whether the event was sent successfully
	// or not.
	Enqueue(conf Config, packet Packet) QueuedEvent

	// Shutdown is called by a client that wishes to stop the flow of
	// events through a SendQueue.
	Shutdown(wait bool)
}

A SendQueue is used by the Sentry client to coordinate the transmission of events. Custom queues can be used to control parallelism and circuit breaking as necessary.

func NewSequentialSendQueue

func NewSequentialSendQueue(buffer int) SendQueue

type Severity

type Severity string

Severity represents a Sentry event severity (ranging from debug to fatal)

type StackTraceOption

type StackTraceOption interface {
	Option
	ForError(err error) StackTraceOption
	WithInternalPrefixes(prefixes ...string) StackTraceOption
}

StackTraceOption wraps a stacktrace and gives you tools for selecting where it is sourced from or what is classified as an internal module.

func StackTrace

func StackTrace() StackTraceOption

StackTrace allows you to add a StackTrace to the event you submit to Sentry, allowing you to quickly determine where in your code the event was generated.

Example
cl := NewClient()

cl.Capture(
	// You can specify that a StackTrace should be included when
	// sending your event to Sentry
	StackTrace().
		// You can also gather the stacktrace frames from a specific
		// error if it is created using `pkg/errors`
		ForError(errors.New("example error")).
		// And you can mark frames as "internal" by specifying the
		// internal frame prefixes here.
		WithInternalPrefixes(
			"github.com/SierraSoftworks/sentry-go",
		),
)
Output:

type Transport

type Transport interface {
	Send(dsn string, packet Packet) error
}

Transport is the interface that any network transport must implement if it wishes to be used to send Sentry events

type UserInfo

type UserInfo struct {
	ID        string
	Email     string
	IPAddress string
	Username  string
	Extra     map[string]string
}

UserInfo provides the fields that may be specified to describe a unique user of your application. You should specify at least an `ID` or `IPAddress`.

Jump to

Keyboard shortcuts

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