sentry-go: github.com/SierraSoftworks/sentry-go Index | Examples | Files

package sentry

import "github.com/SierraSoftworks/sentry-go"

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.

Code:

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

Index

Examples

Package Files

breadcrumb.go breadcrumbs.go client.go config.go contexts.go culprit.go dsn.go environment.go errortype.go eventID.go exception.go extra.go fingerprint.go http.go httpTransport.go httprequest.go logger.go message.go modules.go options.go packet.go platform.go queuedEvent.go release.go sdk.go sendQueue.go sentry-go.go sequentialSendQueue.go servername.go severity.go stacktrace.go stacktraceGen.go tags.go timestamp.go transport.go user.go

Constants

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
    // [DEPRECATED] error is never thrown since Sentry 9 has deprecated the secret key requirement
    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")
)
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")
)
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")
)
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")
)

func AddDefaultOptionProvider Uses

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.

Code:

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

func AddDefaultOptions Uses

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.

Code:

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

func AddInternalPrefixes Uses

func AddInternalPrefixes(prefixes ...string)

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

Code:

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

func NewEventID Uses

func NewEventID() (string, error)

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

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.

Code:

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())
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 Uses

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.

Code:

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

func NewBreadcrumbsList Uses

func NewBreadcrumbsList(size int) BreadcrumbsList

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

type Client Uses

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

Code:

// 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),
)

func DefaultClient Uses

func DefaultClient() Client

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

Code:

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

func NewClient Uses

func NewClient(options ...Option) Client

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

type Config Uses

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 Uses

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 Uses

type ErrType string

func (ErrType) Error Uses

func (e ErrType) Error() string

Error gets the error message for this ErrType

func (ErrType) IsInstance Uses

func (e ErrType) IsInstance(err error) bool

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

type ExceptionInfo Uses

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 Uses

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 Uses

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

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

type FinalizableOption Uses

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 Uses

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 Uses

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 Uses

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 Uses

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.

Code:

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

type MergeableOption Uses

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 Uses

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 Uses

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 Uses

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.

Code:

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

func Context Uses

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 Uses

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/`

Code:

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

func DSN Uses

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.

Code:

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

func DeviceContext Uses

func DeviceContext(info *DeviceContextInfo) Option

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

Code:

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

func Environment Uses

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

Code:

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

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

func EventID Uses

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.

Code:

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

func Exception Uses

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 Uses

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 Uses

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.

Code:

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

func Fingerprint Uses

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

Code:

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

func HTTP Uses

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.

Code:

// 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),
)

func Level Uses

func Level(severity Severity) Option

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

Code:

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

func Logger Uses

func Logger(logger string) Option

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

Code:

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

func Message Uses

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.

Code:

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

func Modules Uses

func Modules(moduleVersions map[string]string) Option

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

Code:

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

func OSContext Uses

func OSContext(info *OSContextInfo) Option

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

Code:

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

func Platform Uses

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.

Code:

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

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

func Release Uses

func Release(version string) Option

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

Code:

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

func RuntimeContext Uses

func RuntimeContext(name, version string) Option

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

Code:

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()),
)

func ServerName Uses

func ServerName(hostname string) Option

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

Code:

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

func Tags Uses

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.

Code:

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

func Timestamp Uses

func Timestamp(timestamp time.Time) Option

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

Code:

cl := NewClient()

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

func UseSendQueue Uses

func UseSendQueue(queue SendQueue) Option

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

Code:

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

func UseTransport Uses

func UseTransport(transport Transport) Option

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

Code:

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

func User Uses

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.

Code:

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

type Packet Uses

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.

Code:

// 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"),
)

func NewPacket Uses

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 Uses

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.

Code:

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

func NewQueuedEvent Uses

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 Uses

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.

Code:

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

type SendQueue Uses

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 Uses

func NewSequentialSendQueue(buffer int) SendQueue

type Severity Uses

type Severity string

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

type StackTraceOption Uses

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 Uses

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.

Code:

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

type Transport Uses

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 Uses

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

Package sentry imports 25 packages (graph). Updated 2019-02-23. Refresh now. Tools for package owners.