Documentation ¶
Overview ¶
Package sentry is the official Sentry SDK for Go.
Use it to report errors and track application performance through distributed tracing.
For more information about Sentry and SDK features please have a look at the documentation site https://docs.sentry.io/platforms/go/.
Basic Usage ¶
The first step is to initialize the SDK, providing at a minimum the DSN of your Sentry project. This step is accomplished through a call to sentry.Init.
func main() { err := sentry.Init(...) ... }
A more detailed yet simple example is available at https://github.com/superlistapp/sentry-go/blob/master/example/basic/main.go.
Error Reporting ¶
The Capture* functions report messages and errors to Sentry.
sentry.CaptureMessage(...) sentry.CaptureException(...) sentry.CaptureEvent(...)
Use similarly named functions in the Hub for concurrent programs like web servers.
Performance Monitoring ¶
You can use Sentry to monitor your application's performance. More information on the product page https://docs.sentry.io/product/performance/.
The StartSpan function creates new spans.
span := sentry.StartSpan(ctx, "operation") ... span.Finish()
Integrations ¶
The SDK has support for several Go frameworks, available as subpackages.
Getting Support ¶
For paid Sentry.io accounts, head out to https://sentry.io/support.
For all users, support channels include:
Forum: https://forum.sentry.io Discord: https://discord.gg/Ww9hbqr (#go channel)
If you found an issue with the SDK, please report through https://github.com/superlistapp/sentry-go/issues/new/choose.
For responsibly disclosing a security issue, please follow the steps in https://sentry.io/security/#vulnerability-disclosure.
Example (TransportWithHooks) ¶
Initializing the SDK with a custom HTTP transport gives a lot of flexibility to inspect requests and responses. This example adds before and after hooks.
package main import ( "fmt" "net/http" "net/http/httputil" "os" "time" "github.com/superlistapp/sentry-go" ) // TransportWithHooks is an http.RoundTripper that wraps an existing // http.RoundTripper adding hooks that run before and after each round trip. type TransportWithHooks struct { http.RoundTripper Before func(*http.Request) error After func(*http.Request, *http.Response, error) (*http.Response, error) } func (t *TransportWithHooks) RoundTrip(req *http.Request) (*http.Response, error) { if err := t.Before(req); err != nil { return nil, err } resp, err := t.RoundTripper.RoundTrip(req) return t.After(req, resp, err) } // Initializing the SDK with a custom HTTP transport gives a lot of flexibility // to inspect requests and responses. This example adds before and after hooks. func main() { err := sentry.Init(sentry.ClientOptions{ // Either set your DSN here or set the SENTRY_DSN environment variable. Dsn: "", Debug: true, HTTPTransport: &TransportWithHooks{ RoundTripper: http.DefaultTransport, Before: func(req *http.Request) error { if b, err := httputil.DumpRequestOut(req, true); err != nil { fmt.Println(err) } else { fmt.Printf("%s\n", b) } return nil }, After: func(req *http.Request, resp *http.Response, err error) (*http.Response, error) { if b, err := httputil.DumpResponse(resp, true); err != nil { fmt.Println(err) } else { fmt.Printf("%s\n", b) } return resp, err }, }, }) if err != nil { fmt.Fprintf(os.Stderr, "sentry.Init: %s\n", err) os.Exit(1) } defer sentry.Flush(2 * time.Second) sentry.CaptureMessage("test") }
Output:
Index ¶
- Constants
- Variables
- func AddBreadcrumb(breadcrumb *Breadcrumb)
- func AddGlobalEventProcessor(processor EventProcessor)
- func ConfigureScope(f func(scope *Scope))
- func Flush(timeout time.Duration) bool
- func HasHubOnContext(ctx context.Context) bool
- func Init(options ClientOptions) error
- func PopScope()
- func PushScope()
- func SetHubOnContext(ctx context.Context, hub *Hub) context.Context
- func WithScope(f func(scope *Scope))
- type Breadcrumb
- type BreadcrumbHint
- type Client
- func (client *Client) AddEventProcessor(processor EventProcessor)
- func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID
- func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID
- func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID
- func (client *Client) Flush(timeout time.Duration) bool
- func (client Client) Options() ClientOptions
- func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID
- func (client *Client) RecoverWithContext(ctx context.Context, err interface{}, hint *EventHint, scope EventModifier) *EventID
- type ClientOptions
- type Dsn
- type DsnParseError
- type Event
- type EventHint
- type EventID
- type EventModifier
- type EventProcessor
- type Exception
- type Frame
- type HTTPSyncTransport
- type HTTPTransport
- type Hub
- func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint)
- func (hub *Hub) BindClient(client *Client)
- func (hub *Hub) CaptureEvent(event *Event) *EventID
- func (hub *Hub) CaptureException(exception error) *EventID
- func (hub *Hub) CaptureMessage(message string) *EventID
- func (hub *Hub) Client() *Client
- func (hub *Hub) Clone() *Hub
- func (hub *Hub) ConfigureScope(f func(scope *Scope))
- func (hub *Hub) Flush(timeout time.Duration) bool
- func (hub *Hub) LastEventID() EventID
- func (hub *Hub) PopScope()
- func (hub *Hub) PushScope() *Scope
- func (hub *Hub) Recover(err interface{}) *EventID
- func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventID
- func (hub *Hub) Scope() *Scope
- func (hub *Hub) WithScope(f func(scope *Scope))
- type Integration
- type Level
- type Request
- type Sampled
- type SamplingContext
- type Scope
- func (scope *Scope) AddBreadcrumb(breadcrumb *Breadcrumb, limit int)
- func (scope *Scope) AddEventProcessor(processor EventProcessor)
- func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint) *Event
- func (scope *Scope) Clear()
- func (scope *Scope) ClearBreadcrumbs()
- func (scope *Scope) Clone() *Scope
- func (scope *Scope) RemoveContext(key string)
- func (scope *Scope) RemoveExtra(key string)
- func (scope *Scope) RemoveTag(key string)
- func (scope *Scope) SetContext(key string, value interface{})
- func (scope *Scope) SetContexts(contexts map[string]interface{})
- func (scope *Scope) SetExtra(key string, value interface{})
- func (scope *Scope) SetExtras(extra map[string]interface{})
- func (scope *Scope) SetFingerprint(fingerprint []string)
- func (scope *Scope) SetLevel(level Level)
- func (scope *Scope) SetRequest(r *http.Request)
- func (scope *Scope) SetRequestBody(b []byte)
- func (scope *Scope) SetTag(key, value string)
- func (scope *Scope) SetTags(tags map[string]string)
- func (scope *Scope) SetTransaction(name string)
- func (scope *Scope) SetUser(user User)
- func (scope *Scope) Transaction() (name string)
- type SdkInfo
- type SdkPackage
- type Span
- type SpanID
- type SpanOption
- type SpanStatus
- type Stacktrace
- type Thread
- type TraceContext
- type TraceID
- type TracesSampler
- type TracesSamplerFunc
- type Transport
- type UniformTracesSampler
- type User
Examples ¶
Constants ¶
const ( // HubContextKey is the key used to store the current Hub. HubContextKey = contextKey(1) // RequestContextKey is the key used to store the current http.Request. RequestContextKey = contextKey(2) )
Keys used to store values in a Context. Use with Context.Value to access values stored by the SDK.
const Version = "0.11.0"
Version is the version of the SDK.
Variables ¶
Logger is an instance of log.Logger that is use to provide debug information about running Sentry Client can be enabled by either using Logger.SetOutput directly or with Debug client option.
Functions ¶
func AddBreadcrumb ¶
func AddBreadcrumb(breadcrumb *Breadcrumb)
AddBreadcrumb records a new breadcrumb.
The total number of breadcrumbs that can be recorded are limited by the configuration on the client.
func AddGlobalEventProcessor ¶
func AddGlobalEventProcessor(processor EventProcessor)
AddGlobalEventProcessor adds processor to the global list of event processors. Global event processors apply to all events.
AddGlobalEventProcessor is deprecated. Most users will prefer to initialize the SDK with Init and provide a ClientOptions.BeforeSend function or use Scope.AddEventProcessor instead.
func ConfigureScope ¶
func ConfigureScope(f func(scope *Scope))
ConfigureScope is a shorthand for CurrentHub().ConfigureScope.
func Flush ¶
Flush waits until the underlying Transport sends any buffered events to the Sentry server, blocking for at most the given timeout. It returns false if the timeout was reached. In that case, some events may not have been sent.
Flush should be called before terminating the program to avoid unintentionally dropping events.
Do not call Flush indiscriminately after every call to CaptureEvent, CaptureException or CaptureMessage. Instead, to have the SDK send events over the network synchronously, configure it to use the HTTPSyncTransport in the call to Init.
func HasHubOnContext ¶
HasHubOnContext checks whether Hub instance is bound to a given Context struct.
func Init ¶
func Init(options ClientOptions) error
Init initializes the SDK with options. The returned error is non-nil if options is invalid, for instance if a malformed DSN is provided.
func SetHubOnContext ¶
SetHubOnContext stores given Hub instance on the Context struct and returns a new Context.
Types ¶
type Breadcrumb ¶
type Breadcrumb struct { Type string `json:"type,omitempty"` Category string `json:"category,omitempty"` Message string `json:"message,omitempty"` Data map[string]interface{} `json:"data,omitempty"` Level Level `json:"level,omitempty"` Timestamp time.Time `json:"timestamp"` }
Breadcrumb specifies an application event that occurred before a Sentry event. An event may contain one or more breadcrumbs.
func (*Breadcrumb) MarshalJSON ¶
func (b *Breadcrumb) MarshalJSON() ([]byte, error)
MarshalJSON converts the Breadcrumb struct to JSON.
type BreadcrumbHint ¶
type BreadcrumbHint map[string]interface{}
BreadcrumbHint contains information that can be associated with a Breadcrumb.
type Client ¶
type Client struct { // Transport is read-only. Replacing the transport of an existing client is // not supported, create a new client instead. Transport Transport // contains filtered or unexported fields }
Client is the underlying processor that is used by the main API and Hub instances. It must be created with NewClient.
func NewClient ¶
func NewClient(options ClientOptions) (*Client, error)
NewClient creates and returns an instance of Client configured using ClientOptions.
Most users will not create clients directly. Instead, initialize the SDK with Init and use the package-level functions (for simple programs that run on a single goroutine) or hub methods (for concurrent programs, for example web servers).
func (*Client) AddEventProcessor ¶
func (client *Client) AddEventProcessor(processor EventProcessor)
AddEventProcessor adds an event processor to the client. It must not be called from concurrent goroutines. Most users will prefer to use ClientOptions.BeforeSend or Scope.AddEventProcessor instead.
Note that typical programs have only a single client created by Init and the client is shared among multiple hubs, one per goroutine, such that adding an event processor to the client affects all hubs that share the client.
func (*Client) CaptureEvent ¶
func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID
CaptureEvent captures an event on the currently active client if any.
The event must already be assembled. Typically code would instead use the utility methods like CaptureException. The return value is the event ID. In case Sentry is disabled or event was dropped, the return value will be nil.
func (*Client) CaptureException ¶
func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID
CaptureException captures an error.
func (*Client) CaptureMessage ¶
func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID
CaptureMessage captures an arbitrary message.
func (*Client) Flush ¶
Flush waits until the underlying Transport sends any buffered events to the Sentry server, blocking for at most the given timeout. It returns false if the timeout was reached. In that case, some events may not have been sent.
Flush should be called before terminating the program to avoid unintentionally dropping events.
Do not call Flush indiscriminately after every call to CaptureEvent, CaptureException or CaptureMessage. Instead, to have the SDK send events over the network synchronously, configure it to use the HTTPSyncTransport in the call to Init.
func (Client) Options ¶
func (client Client) Options() ClientOptions
Options return ClientOptions for the current Client.
func (*Client) Recover ¶
func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID
Recover captures a panic. Returns EventID if successfully, or nil if there's no error to recover from.
func (*Client) RecoverWithContext ¶
func (client *Client) RecoverWithContext( ctx context.Context, err interface{}, hint *EventHint, scope EventModifier, ) *EventID
RecoverWithContext captures a panic and passes relevant context object. Returns EventID if successfully, or nil if there's no error to recover from.
type ClientOptions ¶
type ClientOptions struct { // The DSN to use. If the DSN is not set, the client is effectively // disabled. Dsn string // In debug mode, the debug information is printed to stdout to help you // understand what sentry is doing. Debug bool // Configures whether SDK should generate and attach stacktraces to pure // capture message calls. AttachStacktrace bool // The sample rate for event submission in the range [0.0, 1.0]. By default, // all events are sent. Thus, as a historical special case, the sample rate // 0.0 is treated as if it was 1.0. To drop all events, set the DSN to the // empty string. SampleRate float64 // The sample rate for sampling traces in the range [0.0, 1.0]. TracesSampleRate float64 // Used to customize the sampling of traces, overrides TracesSampleRate. TracesSampler TracesSampler // List of regexp strings that will be used to match against event's message // and if applicable, caught errors type and value. // If the match is found, then a whole event will be dropped. IgnoreErrors []string // BeforeSend is called before error events are sent to Sentry. // Use it to mutate the event or return nil to discard the event. // See EventProcessor if you need to mutate transactions. BeforeSend func(event *Event, hint *EventHint) *Event // Before breadcrumb add callback. BeforeBreadcrumb func(breadcrumb *Breadcrumb, hint *BreadcrumbHint) *Breadcrumb // Integrations to be installed on the current Client, receives default // integrations. Integrations func([]Integration) []Integration // io.Writer implementation that should be used with the Debug mode. DebugWriter io.Writer // The transport to use. Defaults to HTTPTransport. Transport Transport // The server name to be reported. ServerName string // The release to be sent with events. // // Some Sentry features are built around releases, and, thus, reporting // events with a non-empty release improves the product experience. See // https://docs.sentry.io/product/releases/. // // If Release is not set, the SDK will try to derive a default value // from environment variables or the Git repository in the working // directory. // // If you distribute a compiled binary, it is recommended to set the // Release value explicitly at build time. As an example, you can use: // // go build -ldflags='-X main.release=VALUE' // // That will set the value of a predeclared variable 'release' in the // 'main' package to 'VALUE'. Then, use that variable when initializing // the SDK: // // sentry.Init(ClientOptions{Release: release}) // // See https://golang.org/cmd/go/ and https://golang.org/cmd/link/ for // the official documentation of -ldflags and -X, respectively. Release string // The dist to be sent with events. Dist string // The environment to be sent with events. Environment string // Maximum number of breadcrumbs. MaxBreadcrumbs int // An optional pointer to http.Client that will be used with a default // HTTPTransport. Using your own client will make HTTPTransport, HTTPProxy, // HTTPSProxy and CaCerts options ignored. HTTPClient *http.Client // An optional pointer to http.Transport that will be used with a default // HTTPTransport. Using your own transport will make HTTPProxy, HTTPSProxy // and CaCerts options ignored. HTTPTransport http.RoundTripper // An optional HTTP proxy to use. // This will default to the HTTP_PROXY environment variable. HTTPProxy string // An optional HTTPS proxy to use. // This will default to the HTTPS_PROXY environment variable. // HTTPS_PROXY takes precedence over HTTP_PROXY for https requests. HTTPSProxy string // An optional set of SSL certificates to use. CaCerts *x509.CertPool }
ClientOptions that configures a SDK Client.
type Dsn ¶
type Dsn struct {
// contains filtered or unexported fields
}
Dsn is used as the remote address source to client transport.
func NewDsn ¶
NewDsn creates a Dsn by parsing rawURL. Most users will never call this function directly. It is provided for use in custom Transport implementations.
func (Dsn) EnvelopeAPIURL ¶
EnvelopeAPIURL returns the URL of the envelope endpoint of the project associated with the DSN.
func (Dsn) MarshalJSON ¶
MarshalJSON converts the Dsn struct to JSON.
func (Dsn) RequestHeaders ¶
RequestHeaders returns all the necessary headers that have to be used in the transport.
func (Dsn) StoreAPIURL ¶
StoreAPIURL returns the URL of the store endpoint of the project associated with the DSN.
func (*Dsn) UnmarshalJSON ¶
UnmarshalJSON converts JSON data to the Dsn struct.
type DsnParseError ¶
type DsnParseError struct {
Message string
}
DsnParseError represents an error that occurs if a Sentry DSN cannot be parsed.
func (DsnParseError) Error ¶
func (e DsnParseError) Error() string
type Event ¶
type Event struct { Breadcrumbs []*Breadcrumb `json:"breadcrumbs,omitempty"` Contexts map[string]interface{} `json:"contexts,omitempty"` Dist string `json:"dist,omitempty"` Environment string `json:"environment,omitempty"` EventID EventID `json:"event_id,omitempty"` Extra map[string]interface{} `json:"extra,omitempty"` Fingerprint []string `json:"fingerprint,omitempty"` Level Level `json:"level,omitempty"` Message string `json:"message,omitempty"` Platform string `json:"platform,omitempty"` Release string `json:"release,omitempty"` Sdk SdkInfo `json:"sdk,omitempty"` ServerName string `json:"server_name,omitempty"` Threads []Thread `json:"threads,omitempty"` Tags map[string]string `json:"tags,omitempty"` Timestamp time.Time `json:"timestamp"` Transaction string `json:"transaction,omitempty"` User User `json:"user,omitempty"` Logger string `json:"logger,omitempty"` Modules map[string]string `json:"modules,omitempty"` Request *Request `json:"request,omitempty"` Exception []Exception `json:"exception,omitempty"` Type string `json:"type,omitempty"` StartTime time.Time `json:"start_timestamp"` Spans []*Span `json:"spans,omitempty"` }
Event is the fundamental data structure that is sent to Sentry.
func (*Event) MarshalJSON ¶
MarshalJSON converts the Event struct to JSON.
type EventHint ¶
type EventHint struct { Data interface{} EventID string OriginalException error RecoveredException interface{} Context context.Context Request *http.Request Response *http.Response }
EventHint contains information that can be associated with an Event.
type EventID ¶
type EventID string
EventID is a hexadecimal string representing a unique uuid4 for an Event. An EventID must be 32 characters long, lowercase and not have any dashes.
func CaptureEvent ¶
CaptureEvent captures an event on the currently active client if any.
The event must already be assembled. Typically code would instead use the utility methods like CaptureException. The return value is the event ID. In case Sentry is disabled or event was dropped, the return value will be nil.
func CaptureException ¶
CaptureException captures an error.
func CaptureMessage ¶
CaptureMessage captures an arbitrary message.
func RecoverWithContext ¶
RecoverWithContext captures a panic and passes relevant context object.
type EventModifier ¶
EventModifier is the interface that wraps the ApplyToEvent method.
ApplyToEvent changes an event based on external data and/or an event hint.
type EventProcessor ¶
EventProcessor is a function that processes an event. Event processors are used to change an event before it is sent to Sentry.
type Exception ¶
type Exception struct { Type string `json:"type,omitempty"` // used as the main issue title Value string `json:"value,omitempty"` // used as the main issue subtitle Module string `json:"module,omitempty"` ThreadID string `json:"thread_id,omitempty"` Stacktrace *Stacktrace `json:"stacktrace,omitempty"` }
Exception specifies an error that occurred.
type Frame ¶
type Frame struct { Function string `json:"function,omitempty"` Symbol string `json:"symbol,omitempty"` Module string `json:"module,omitempty"` Package string `json:"package,omitempty"` Filename string `json:"filename,omitempty"` AbsPath string `json:"abs_path,omitempty"` Lineno int `json:"lineno,omitempty"` Colno int `json:"colno,omitempty"` PreContext []string `json:"pre_context,omitempty"` ContextLine string `json:"context_line,omitempty"` PostContext []string `json:"post_context,omitempty"` InApp bool `json:"in_app,omitempty"` Vars map[string]interface{} `json:"vars,omitempty"` }
Frame represents a function call and it's metadata. Frames are associated with a Stacktrace.
type HTTPSyncTransport ¶
type HTTPSyncTransport struct { // HTTP Client request timeout. Defaults to 30 seconds. Timeout time.Duration // contains filtered or unexported fields }
HTTPSyncTransport is a blocking implementation of Transport.
Clients using this transport will send requests to Sentry sequentially and block until a response is returned.
The blocking behavior is useful in a limited set of use cases. For example, use it when deploying code to a Function as a Service ("Serverless") platform, where any work happening in a background goroutine is not guaranteed to execute.
For most cases, prefer HTTPTransport.
func NewHTTPSyncTransport ¶
func NewHTTPSyncTransport() *HTTPSyncTransport
NewHTTPSyncTransport returns a new pre-configured instance of HTTPSyncTransport.
func (*HTTPSyncTransport) Configure ¶
func (t *HTTPSyncTransport) Configure(options ClientOptions)
Configure is called by the Client itself, providing it it's own ClientOptions.
func (*HTTPSyncTransport) Flush ¶
func (t *HTTPSyncTransport) Flush(_ time.Duration) bool
Flush is a no-op for HTTPSyncTransport. It always returns true immediately.
func (*HTTPSyncTransport) SendEvent ¶
func (t *HTTPSyncTransport) SendEvent(event *Event)
SendEvent assembles a new packet out of Event and sends it to remote server.
type HTTPTransport ¶
type HTTPTransport struct { // Size of the transport buffer. Defaults to 30. BufferSize int // HTTP Client request timeout. Defaults to 30 seconds. Timeout time.Duration // contains filtered or unexported fields }
HTTPTransport is the default, non-blocking, implementation of Transport.
Clients using this transport will enqueue requests in a buffer and return to the caller before any network communication has happened. Requests are sent to Sentry sequentially from a background goroutine.
func NewHTTPTransport ¶
func NewHTTPTransport() *HTTPTransport
NewHTTPTransport returns a new pre-configured instance of HTTPTransport.
func (*HTTPTransport) Configure ¶
func (t *HTTPTransport) Configure(options ClientOptions)
Configure is called by the Client itself, providing it it's own ClientOptions.
func (*HTTPTransport) Flush ¶
func (t *HTTPTransport) Flush(timeout time.Duration) bool
Flush waits until any buffered events are sent to the Sentry server, blocking for at most the given timeout. It returns false if the timeout was reached. In that case, some events may not have been sent.
Flush should be called before terminating the program to avoid unintentionally dropping events.
Do not call Flush indiscriminately after every call to SendEvent. Instead, to have the SDK send events over the network synchronously, configure it to use the HTTPSyncTransport in the call to Init.
func (*HTTPTransport) SendEvent ¶
func (t *HTTPTransport) SendEvent(event *Event)
SendEvent assembles a new packet out of Event and sends it to remote server.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the central object that manages scopes and clients.
This can be used to capture events and manage the scope. The default hub that is available automatically.
In most situations developers do not need to interface the hub. Instead toplevel convenience functions are exposed that will automatically dispatch to global (CurrentHub) hub. In some situations this might not be possible in which case it might become necessary to manually work with the hub. This is for instance the case when working with async code.
func CurrentHub ¶
func CurrentHub() *Hub
CurrentHub returns an instance of previously initialized Hub stored in the global namespace.
func GetHubFromContext ¶
GetHubFromContext tries to retrieve Hub instance from the given Context struct or return nil if one is not found.
func (*Hub) AddBreadcrumb ¶
func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint)
AddBreadcrumb records a new breadcrumb.
The total number of breadcrumbs that can be recorded are limited by the configuration on the client.
func (*Hub) BindClient ¶
BindClient binds a new Client for the current Hub.
func (*Hub) CaptureEvent ¶
CaptureEvent calls the method of a same name on currently bound Client instance passing it a top-level Scope. Returns EventID if successfully, or nil if there's no Scope or Client available.
func (*Hub) CaptureException ¶
CaptureException calls the method of a same name on currently bound Client instance passing it a top-level Scope. Returns EventID if successfully, or nil if there's no Scope or Client available.
func (*Hub) CaptureMessage ¶
CaptureMessage calls the method of a same name on currently bound Client instance passing it a top-level Scope. Returns EventID if successfully, or nil if there's no Scope or Client available.
func (*Hub) Client ¶
Client returns top-level Client of the current Hub or nil if no Client is bound.
func (*Hub) Clone ¶
Clone returns a copy of the current Hub with top-most scope and client copied over.
func (*Hub) ConfigureScope ¶
ConfigureScope runs f in the current scope.
It is useful to set data that applies to all events that share the current scope.
Modifying the scope affects all references to the current scope.
See also WithScope for making isolated temporary changes.
func (*Hub) Flush ¶
Flush waits until the underlying Transport sends any buffered events to the Sentry server, blocking for at most the given timeout. It returns false if the timeout was reached. In that case, some events may not have been sent.
Flush should be called before terminating the program to avoid unintentionally dropping events.
Do not call Flush indiscriminately after every call to CaptureEvent, CaptureException or CaptureMessage. Instead, to have the SDK send events over the network synchronously, configure it to use the HTTPSyncTransport in the call to Init.
func (*Hub) LastEventID ¶
LastEventID returns an ID of last captured event for the current Hub.
func (*Hub) PopScope ¶
func (hub *Hub) PopScope()
PopScope drops the most recent scope.
Calls to PopScope must be coordinated with PushScope. For most cases, using WithScope should be more convenient.
Calls to PopScope that do not match previous calls to PushScope are silently ignored.
func (*Hub) PushScope ¶
PushScope pushes a new scope for the current Hub and reuses previously bound Client.
func (*Hub) Recover ¶
Recover calls the method of a same name on currently bound Client instance passing it a top-level Scope. Returns EventID if successfully, or nil if there's no Scope or Client available.
func (*Hub) RecoverWithContext ¶
RecoverWithContext calls the method of a same name on currently bound Client instance passing it a top-level Scope. Returns EventID if successfully, or nil if there's no Scope or Client available.
func (*Hub) WithScope ¶
WithScope runs f in an isolated temporary scope.
It is useful when extra data should be sent with a single capture call, for instance a different level or tags.
The scope passed to f starts as a clone of the current scope and can be freely modified without affecting the current scope.
It is a shorthand for PushScope followed by PopScope.
type Integration ¶
Integration allows for registering a functions that modify or discard captured events.
type Request ¶
type Request struct { URL string `json:"url,omitempty"` Method string `json:"method,omitempty"` Data string `json:"data,omitempty"` QueryString string `json:"query_string,omitempty"` Cookies string `json:"cookies,omitempty"` Headers map[string]string `json:"headers,omitempty"` Env map[string]string `json:"env,omitempty"` }
Request contains information on a HTTP request related to the event.
func NewRequest ¶
NewRequest returns a new Sentry Request from the given http.Request.
NewRequest avoids operations that depend on network access. In particular, it does not read r.Body.
type Sampled ¶
type Sampled int8
Sampled signifies a sampling decision.
The possible trace sampling decisions are: SampledFalse, SampledUndefined (default) and SampledTrue.
type SamplingContext ¶
type SamplingContext struct { Span *Span // The current span, always non-nil. Parent *Span // The parent span, may be nil. }
A SamplingContext is passed to a TracesSampler to determine a sampling decision.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope holds contextual data for the current scope.
The scope is an object that can cloned efficiently and stores data that is locally relevant to an event. For instance the scope will hold recorded breadcrumbs and similar information.
The scope can be interacted with in two ways. First, the scope is routinely updated with information by functions such as AddBreadcrumb which will modify the current scope. Second, the current scope can be configured through the ConfigureScope function or Hub method of the same name.
The scope is meant to be modified but not inspected directly. When preparing an event for reporting, the current client adds information from the current scope into the event.
func (*Scope) AddBreadcrumb ¶
func (scope *Scope) AddBreadcrumb(breadcrumb *Breadcrumb, limit int)
AddBreadcrumb adds new breadcrumb to the current scope and optionally throws the old one if limit is reached.
func (*Scope) AddEventProcessor ¶
func (scope *Scope) AddEventProcessor(processor EventProcessor)
AddEventProcessor adds an event processor to the current scope.
func (*Scope) ApplyToEvent ¶
ApplyToEvent takes the data from the current scope and attaches it to the event.
func (*Scope) Clear ¶
func (scope *Scope) Clear()
Clear removes the data from the current scope. Not safe for concurrent use.
func (*Scope) ClearBreadcrumbs ¶
func (scope *Scope) ClearBreadcrumbs()
ClearBreadcrumbs clears all breadcrumbs from the current scope.
func (*Scope) RemoveContext ¶
RemoveContext removes a context from the current scope.
func (*Scope) RemoveExtra ¶
RemoveExtra removes a extra from the current scope.
func (*Scope) SetContext ¶
SetContext adds a context to the current scope.
func (*Scope) SetContexts ¶
SetContexts assigns multiple contexts to the current scope.
func (*Scope) SetFingerprint ¶
SetFingerprint sets new fingerprint for the current scope.
func (*Scope) SetRequest ¶
SetRequest sets the request for the current scope.
func (*Scope) SetRequestBody ¶
SetRequestBody sets the request body for the current scope.
This method should only be called when the body bytes are already available in memory. Typically, the request body is buffered lazily from the Request.Body from SetRequest.
func (*Scope) SetTransaction ¶
SetTransaction sets the transaction name for the current transaction.
func (*Scope) Transaction ¶
Transaction returns the transaction name for the current transaction.
type SdkInfo ¶
type SdkInfo struct { Name string `json:"name,omitempty"` Version string `json:"version,omitempty"` Integrations []string `json:"integrations,omitempty"` Packages []SdkPackage `json:"packages,omitempty"` }
SdkInfo contains all metadata about about the SDK being used.
type SdkPackage ¶
type SdkPackage struct { Name string `json:"name,omitempty"` Version string `json:"version,omitempty"` }
SdkPackage describes a package that was installed.
type Span ¶
type Span struct { TraceID TraceID `json:"trace_id"` SpanID SpanID `json:"span_id"` ParentSpanID SpanID `json:"parent_span_id"` Op string `json:"op,omitempty"` Description string `json:"description,omitempty"` Status SpanStatus `json:"status,omitempty"` Tags map[string]string `json:"tags,omitempty"` StartTime time.Time `json:"start_timestamp"` EndTime time.Time `json:"timestamp"` Data map[string]interface{} `json:"data,omitempty"` Sampled Sampled `json:"-"` // contains filtered or unexported fields }
A Span is the building block of a Sentry transaction. Spans build up a tree structure of timed operations. The span tree makes up a transaction event that is sent to Sentry when the root span is finished.
Spans must be started with either StartSpan or Span.StartChild.
func StartSpan ¶
func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Span
StartSpan starts a new span to describe an operation. The new span will be a child of the last span stored in ctx, if any.
One or more options can be used to modify the span properties. Typically one option as a function literal is enough. Combining multiple options can be useful to define and reuse specific properties with named functions.
Caller should call the Finish method on the span to mark its end. Finishing a root span sends the span and all of its children, recursively, as a transaction to Sentry.
func TransactionFromContext ¶
TransactionFromContext returns the root span of the current transaction. It returns nil if no transaction is tracked in the context.
func (*Span) Finish ¶
func (s *Span) Finish()
Finish sets the span's end time, unless already set. If the span is the root of a span tree, Finish sends the span tree to Sentry as a transaction.
func (*Span) MarshalJSON ¶
func (*Span) SetTag ¶
SetTag sets a tag on the span. It is recommended to use SetTag instead of accessing the tags map directly as SetTag takes care of initializing the map when necessary.
func (*Span) StartChild ¶
func (s *Span) StartChild(operation string, options ...SpanOption) *Span
StartChild starts a new child span.
The call span.StartChild(operation, options...) is a shortcut for StartSpan(span.Context(), operation, options...).
func (*Span) ToSentryTrace ¶
ToSentryTrace returns the trace propagation value used with the sentry-trace HTTP header.
type SpanOption ¶
type SpanOption func(s *Span)
A SpanOption is a function that can modify the properties of a span.
func ContinueFromRequest ¶
func ContinueFromRequest(r *http.Request) SpanOption
ContinueFromRequest returns a span option that updates the span to continue an existing trace. If it cannot detect an existing trace in the request, the span will be left unchanged.
func TransactionName ¶
func TransactionName(name string) SpanOption
The TransactionName option sets the name of the current transaction.
A span tree has a single transaction name, therefore using this option when starting a span affects the span tree as a whole, potentially overwriting a name set previously.
type SpanStatus ¶
type SpanStatus uint8
SpanStatus is the status of a span.
const ( SpanStatusUndefined SpanStatus = iota SpanStatusOK SpanStatusCanceled SpanStatusUnknown SpanStatusInvalidArgument SpanStatusDeadlineExceeded SpanStatusNotFound SpanStatusAlreadyExists SpanStatusPermissionDenied SpanStatusResourceExhausted SpanStatusFailedPrecondition SpanStatusAborted SpanStatusOutOfRange SpanStatusUnimplemented SpanStatusInternalError SpanStatusDataLoss SpanStatusUnauthenticated )
func (SpanStatus) MarshalJSON ¶
func (ss SpanStatus) MarshalJSON() ([]byte, error)
func (SpanStatus) String ¶
func (ss SpanStatus) String() string
type Stacktrace ¶
type Stacktrace struct { Frames []Frame `json:"frames,omitempty"` FramesOmitted []uint `json:"frames_omitted,omitempty"` }
Stacktrace holds information about the frames of the stack.
func ExtractStacktrace ¶
func ExtractStacktrace(err error) *Stacktrace
ExtractStacktrace creates a new Stacktrace based on the given error.
func NewStacktrace ¶
func NewStacktrace() *Stacktrace
NewStacktrace creates a stacktrace using runtime.Callers.
type Thread ¶
type Thread struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Stacktrace *Stacktrace `json:"stacktrace,omitempty"` Crashed bool `json:"crashed,omitempty"` Current bool `json:"current,omitempty"` }
Thread specifies threads that were running at the time of an event.
type TraceContext ¶
type TraceContext struct { TraceID TraceID `json:"trace_id"` SpanID SpanID `json:"span_id"` ParentSpanID SpanID `json:"parent_span_id"` Op string `json:"op,omitempty"` Description string `json:"description,omitempty"` Status SpanStatus `json:"status,omitempty"` }
A TraceContext carries information about an ongoing trace and is meant to be stored in Event.Contexts (as *TraceContext).
func (*TraceContext) MarshalJSON ¶
func (tc *TraceContext) MarshalJSON() ([]byte, error)
type TracesSampler ¶
type TracesSampler interface {
Sample(ctx SamplingContext) Sampled
}
A TracesSampler makes sampling decisions for spans.
In addition to the sampling context passed to the Sample method, implementations may keep and use internal state to make decisions.
Sampling is one of the last steps when starting a new span, such that the sampler can inspect most of the state of the span to make a decision.
Implementations must be safe for concurrent use by multiple goroutines.
type TracesSamplerFunc ¶
type TracesSamplerFunc func(ctx SamplingContext) Sampled
The TracesSamplerFunc type is an adapter to allow the use of ordinary functions as a TracesSampler.
func (TracesSamplerFunc) Sample ¶
func (f TracesSamplerFunc) Sample(ctx SamplingContext) Sampled
type Transport ¶
type Transport interface { Flush(timeout time.Duration) bool Configure(options ClientOptions) SendEvent(event *Event) }
Transport is used by the Client to deliver events to remote server.
type UniformTracesSampler ¶
type UniformTracesSampler float64
UniformTracesSampler is a TracesSampler that samples root spans randomly at a uniform rate.
func (UniformTracesSampler) Sample ¶
func (s UniformTracesSampler) Sample(ctx SamplingContext) Sampled
type User ¶
type User struct { Email string `json:"email,omitempty"` ID string `json:"id,omitempty"` IPAddress string `json:"ip_address,omitempty"` Username string `json:"username,omitempty"` }
User describes the user associated with an Event. If this is used, at least an ID or an IP address should be provided.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
example
|
|
basic
This is an example program that makes an HTTP request and prints response headers.
|
This is an example program that makes an HTTP request and prints response headers. |
http
This is an example web server to demonstrate how to instrument error and performance monitoring with Sentry.
|
This is an example web server to demonstrate how to instrument error and performance monitoring with Sentry. |
recover-repanic
This is an example program that demonstrates an advanced use of the Sentry SDK using Hub, Scope and EventProcessor to recover from runtime panics, report to Sentry filtering specific frames from the stack trace and then letting the program crash as usual.
|
This is an example program that demonstrates an advanced use of the Sentry SDK using Hub, Scope and EventProcessor to recover from runtime panics, report to Sentry filtering specific frames from the stack trace and then letting the program crash as usual. |
Package sentryhttp provides Sentry integration for servers based on the net/http package.
|
Package sentryhttp provides Sentry integration for servers based on the net/http package. |
internal
|
|
ratelimit
Package ratelimit provides tools to work with rate limits imposed by Sentry's data ingestion pipeline.
|
Package ratelimit provides tools to work with rate limits imposed by Sentry's data ingestion pipeline. |