sentry

package module
v1.0.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 39 Imported by: 3,587

README

Sentry

Official Sentry SDK for Go

Build Status Go Report Card Discord X Follow go.dev

sentry-go provides a Sentry client implementation for the Go programming language. This is the next generation of the Go SDK for Sentry, intended to replace the raven-go package.

Looking for the old raven-go SDK documentation? See the Legacy client section here. If you want to start using sentry-go instead, check out the migration guide.

Requirements

The only requirement is a Go compiler.

We follow Go's official release policy, supporting the two most recent Go releases. Each major Go release is supported until there are two newer major releases. The exact versions are defined in GitHub workflow.

In addition, we run tests against the current master branch of the Go toolchain, though support for this configuration is best-effort.

Installation

sentry-go can be installed like any other Go library through go get:

$ go get github.com/getsentry/sentry-go@latest

Check out the list of released versions.

Configuration

To use sentry-go, you’ll need to import the sentry-go package and initialize it with your DSN and other options.

If not specified in the SDK initialization, the DSN, Release and Environment are read from the environment variables SENTRY_DSN, SENTRY_RELEASE and SENTRY_ENVIRONMENT, respectively.

More on this in the Configuration section of the official Sentry Go SDK documentation.

Usage

The SDK supports reporting errors and tracking application performance.

To get started, have a look at one of our examples:

We also provide a complete API reference.

For more detailed information about how to get the most out of sentry-go, check out the official documentation:

Resources

License

Licensed under The MIT License, see LICENSE.

Community

Join Sentry's #go channel on Discord to get involved and help us improve the SDK!

Documentation

Overview

Package repository: https://github.com/getsentry/sentry-go/

For more information about Sentry and SDK features, please have a look at the official documentation site: https://docs.sentry.io/platforms/go/

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 (
	"context"
	"fmt"
	"net/http"
	"net/http/httputil"
	"os"
	"time"

	"github.com/getsentry/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(_ *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(context.Background(), "test")
}

Index

Examples

Constants

View Source
const (
	MechanismTypeGeneric string = "generic"
	MechanismTypeChained string = "chained"
	MechanismTypeUnwrap  string = "unwrap"
	MechanismSourceCause string = "cause"
)
View Source
const (
	LogSeverityTrace   int = 1
	LogSeverityDebug   int = 5
	LogSeverityInfo    int = 9
	LogSeverityWarning int = 13
	LogSeverityError   int = 17
	LogSeverityFatal   int = 21
)
View Source
const (
	UnitNanosecond  = "nanosecond"
	UnitMicrosecond = "microsecond"
	UnitMillisecond = "millisecond"
	UnitSecond      = "second"
	UnitMinute      = "minute"
	UnitHour        = "hour"
	UnitDay         = "day"
	UnitWeek        = "week"
)

Duration Units.

View Source
const (
	UnitBit      = "bit"
	UnitByte     = "byte"
	UnitKilobyte = "kilobyte"
	UnitKibibyte = "kibibyte"
	UnitMegabyte = "megabyte"
	UnitMebibyte = "mebibyte"
	UnitGigabyte = "gigabyte"
	UnitGibibyte = "gibibyte"
	UnitTerabyte = "terabyte"
	UnitTebibyte = "tebibyte"
	UnitPetabyte = "petabyte"
	UnitPebibyte = "pebibyte"
	UnitExabyte  = "exabyte"
	UnitExbibyte = "exbibyte"
)

Information Units.

View Source
const (
	UnitRatio   = "ratio"
	UnitPercent = "percent"
)

Fraction Units.

View Source
const (
	SentryTraceHeader   = "sentry-trace"
	SentryBaggageHeader = "baggage"
	TraceparentHeader   = "traceparent"
)
View Source
const (
	SpanOriginManual   = "manual"
	SpanOriginEcho     = "auto.http.echo"
	SpanOriginFastHTTP = "auto.http.fasthttp"
	SpanOriginFiber    = "auto.http.fiber"
	SpanOriginGin      = "auto.http.gin"
	SpanOriginStdLib   = "auto.http.stdlib"
	SpanOriginIris     = "auto.http.iris"
	SpanOriginNegroni  = "auto.http.negroni"
	SpanOriginGrpc     = "auto.rpc.grpc"
)
View Source
const DefaultFlushTimeout = 2 * time.Second

DefaultFlushTimeout is the default timeout used for flushing events.

View Source
const SDKVersion = "1.0.0-alpha.1"

The version of the SDK.

Variables

View Source
var (
	ErrTransportQueueFull = telemetry.ErrQueueFull
	ErrTransportClosed    = errors.New("transport is closed")
	ErrInvalidEnvelope    = errors.New("invalid envelope: missing header or items")
)
View Source
var DebugLogger = debuglog.GetLogger()

DebugLogger is an instance of log.Logger that is used to provide debug information about running Sentry Client can be enabled by either using debuglog.SetOutput directly or with Debug client option.

View Source
var RequestContextKey requestContextKey

RequestContextKey is the key used to store the current request object in a capture context.

Functions

func AddBreadcrumb

func AddBreadcrumb(ctx context.Context, breadcrumb *Breadcrumb, options ...BreadcrumbOption)

AddBreadcrumb records a new breadcrumb using the scope and client carried by ctx. The breadcrumb is dropped when ctx carries no scope.

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 ContextWithClient

func ContextWithClient(ctx context.Context, client *Client) context.Context

ContextWithClient returns a derived context that routes telemetry through client without changing its scope. A nil client leaves ctx unchanged.

func ContextWithScope

func ContextWithScope(ctx context.Context, scope *Scope) context.Context

ContextWithScope returns a context carrying scope. A nil scope leaves ctx unchanged.

func Flush

func Flush(timeout time.Duration) bool

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 capture is disabled or the timeout was reached. In the latter 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 FlushWithContext added in v0.34.0

func FlushWithContext(ctx context.Context) bool

func GetBaggage

func GetBaggage(ctx context.Context) string

GetBaggage returns the Sentry baggage header value carried by ctx.

func GetTraceparent

func GetTraceparent(ctx context.Context) string

GetTraceparent returns the sentry-trace header value carried by ctx. The sentry-trace header is distinct from the W3C traceparent header, which can be obtained using `GetTraceparentW3C`.

func GetTraceparentW3C

func GetTraceparentW3C(ctx context.Context) string

GetTraceparentW3C returns the W3C traceparent header value carried by ctx.

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 MergeBaggage added in v0.46.0

func MergeBaggage(existingHeader, sentryHeader string) (string, error)

MergeBaggage merges an existing baggage header with a Sentry-generated one.

Existing third-party members are preserved while stale Sentry members are replaced by the generated baggage. The helper is best-effort and only keeps the Sentry baggage in case the existing one is malformed.

func Pointer added in v0.28.0

func Pointer[T any](v T) *T

func WithMonitor added in v0.50.0

func WithMonitor(ctx context.Context, monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error

WithMonitor runs fn and reports its outcome as check-ins for the cron monitor identified by monitorSlug, using the scope and client carried by ctx.

An in_progress check-in carrying monitorConfig is sent before fn runs. When monitorConfig is not nil, Sentry creates the monitor if it does not exist, or updates its configuration. After fn returns, an ok check-in is sent if it returned nil, or an error check-in otherwise, along with the measured duration. If fn panics, an error check-in is sent and the panic continues.

The error returned by fn is returned unchanged.

Types

type Attachment added in v0.23.0

type Attachment struct {
	Filename    string
	ContentType string
	Payload     []byte
}

Attachment allows associating files with your events to aid in investigation. An event may contain one or more attachments.

type BodyType added in v0.48.0

type BodyType string

BodyType identifies a category of HTTP body to collect.

const (
	// BodyIncomingRequest collects bodies from incoming HTTP requests
	// (server-side).
	BodyIncomingRequest BodyType = "incomingRequest"

	// BodyOutgoingRequest collects bodies from outgoing HTTP requests
	// (client-side).
	BodyOutgoingRequest BodyType = "outgoingRequest"

	// BodyIncomingResponse collects bodies from incoming HTTP responses
	// (client-side).
	BodyIncomingResponse BodyType = "incomingResponse"
)
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,omitzero"`
}

Breadcrumb specifies an application event that occurred before a Sentry event. An event may contain one or more breadcrumbs.

type BreadcrumbHint map[string]interface{}

BreadcrumbHint contains information that can be associated with a Breadcrumb.

type BreadcrumbOption func(*breadcrumbOptions)

BreadcrumbOption configures a single breadcrumb operation.

func WithBreadcrumbHint

func WithBreadcrumbHint(hint *BreadcrumbHint) BreadcrumbOption

WithBreadcrumbHint supplies metadata to the before-breadcrumb callback.

type CaptureOption

type CaptureOption func(*captureOptions)

CaptureOption configures a single event capture.

func WithEventHint

func WithEventHint(hint *EventHint) CaptureOption

WithEventHint supplies metadata to event processors and before-send hooks.

func WithLevel

func WithLevel(level Level) CaptureOption

WithLevel sets the event level for a single capture.

type CheckIn added in v0.23.0

type CheckIn struct {
	// Check-In ID (unique and client generated)
	ID EventID `json:"check_in_id"`
	// The distinct slug of the monitor.
	MonitorSlug string `json:"monitor_slug"`
	// The status of the check-in.
	Status CheckInStatus `json:"status"`
	// The duration of the check-in. Will only take effect if the status is ok or error.
	Duration time.Duration `json:"duration,omitempty"`
}

type CheckInStatus added in v0.23.0

type CheckInStatus string
const (
	CheckInStatusInProgress CheckInStatus = "in_progress"
	CheckInStatusOK         CheckInStatus = "ok"
	CheckInStatusError      CheckInStatus = "error"
)

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 processes telemetry captured through the SDK. It must be created with NewClient.

func ClientFromContext

func ClientFromContext(ctx context.Context) *Client

ClientFromContext returns the client attached to ctx, or the global client.

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 capture functions. Server applications should pass an isolated request context to those functions.

func NewNoopClient added in v0.50.0

func NewNoopClient() *Client

NewNoopClient returns the shared client that safely discards telemetry. Its mutating methods have no effect.

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 can be shared by multiple contexts, such that adding an event processor affects all contexts that share the client.

func (*Client) CaptureCheckIn added in v0.23.0

func (client *Client) CaptureCheckIn(
	ctx context.Context,
	checkIn *CheckIn,
	monitorConfig *MonitorConfig,
	options ...CaptureOption,
) *EventID

CaptureCheckIn captures a check-in using the scope carried by ctx.

func (*Client) CaptureEvent

func (client *Client) CaptureEvent(ctx context.Context, event *Event, options ...CaptureOption) *EventID

CaptureEvent captures an event using the scope carried by ctx.

func (*Client) CaptureException

func (client *Client) CaptureException(ctx context.Context, exception error, options ...CaptureOption) *EventID

CaptureException captures an error using the scope carried by ctx.

func (*Client) CaptureMessage

func (client *Client) CaptureMessage(ctx context.Context, message string, options ...CaptureOption) *EventID

CaptureMessage captures an arbitrary message using the scope carried by ctx.

func (*Client) Close added in v0.31.0

func (client *Client) Close()

Close clean up underlying Transport resources.

Close should be called after Flush and before terminating the program otherwise some events may be lost.

func (*Client) Flush

func (client *Client) Flush(timeout time.Duration) bool

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 client is disabled or the timeout was reached. In the latter 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) FlushWithContext added in v0.34.0

func (client *Client) FlushWithContext(ctx context.Context) bool

FlushWithContext waits until the underlying Transport sends any buffered events to the Sentry server, blocking for at most the duration specified by the context. It returns false if the client is disabled or the context is canceled before the events are sent. In the latter case, some events may not be delivered.

FlushWithContext should be called before terminating the program to ensure no events are unintentionally dropped.

Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent, CaptureException, or CaptureMessage. To send events synchronously over the network, configure the SDK to use HTTPSyncTransport during initialization with Init.

func (*Client) GetDataCollection added in v0.48.0

func (client *Client) GetDataCollection() DataCollection

GetDataCollection returns a copy of the resolved data collection configuration used by the client.

func (*Client) GetSDKIdentifier added in v0.24.0

func (client *Client) GetSDKIdentifier() string

func (*Client) IsEnabled added in v0.50.0

func (client *Client) IsEnabled() bool

IsEnabled reports whether the client processes captured telemetry.

It returns false for a nil receiver and for clients returned by NewNoopClient. A client can be enabled while using a transport that discards telemetry, such as a client configured with an empty DSN.

func (*Client) Options

func (client *Client) Options() ClientOptions

Options return ClientOptions for the current Client.

func (*Client) SetSDKIdentifier added in v0.24.0

func (client *Client) SetSDKIdentifier(identifier string)

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, diagnostic information is written to DebugWriter, which
	// defaults to stderr.
	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
	// Enable performance tracing.
	EnableTracing bool
	// 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
	// Control with URLs trace propagation should be enabled. Does not support regex patterns.
	TracePropagationTargets []string
	// PropagateTraceparent is used to control whether the W3C Trace Context HTTP traceparent header
	// is propagated on outgoing http requests.
	PropagateTraceparent bool
	// StrictTraceContinuation is used to control trace continuation from 3rd party services that happen to be
	// instrumented by Sentry.
	//
	// Enabling the option means that the SDK will require the org ids from baggage to match for continuing the trace.
	StrictTraceContinuation bool
	// OrgID configures the orgID used for trace propagation and features like StrictTraceContinuation.
	//
	// In most cases the orgID is already parsed from the DSN. This option should be used when non-standard Sentry DSNs
	// are used, such as self-hosted or when using a local Relay.
	OrgID uint64
	// 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
	// List of regexp strings that will be used to match against a transaction's
	// name.  If a match is found, then the transaction  will be dropped.
	IgnoreTransactions []string
	// Deprecated: Use DataCollection for granular control over what data the
	// SDK collects. When DataCollection is configured, SendDefaultPII is
	// ignored.
	//
	// If this flag is enabled, certain personally identifiable information (PII) is added by active integrations.
	// By default, no such data is sent.
	SendDefaultPII bool
	// DataCollection configures what data the SDK collects automatically. All fields are optional. By default
	// the SDK collects rich context for debugging while scrubbing sensitive values.
	//
	// See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection
	DataCollection *DataCollection
	// BeforeSend is called before error events are sent to Sentry.
	// You can use it to mutate the event or return nil to discard it.
	BeforeSend func(event *Event, hint *EventHint) *Event
	// BeforeSendLong is called before log events are sent to Sentry.
	// You can use it to mutate the log event or return nil to discard it.
	BeforeSendLog func(event *Log) *Log
	// BeforeSendTransaction is called before transaction events are sent to Sentry.
	// Use it to mutate the transaction or return nil to discard the transaction.
	BeforeSendTransaction func(event *Event, hint *EventHint) *Event
	// Before breadcrumb add callback.
	BeforeBreadcrumb func(breadcrumb *Breadcrumb, hint *BreadcrumbHint) *Breadcrumb
	// BeforeSendMetric is called before metric events are sent to Sentry.
	// You can use it to mutate the metric or return nil to discard it.
	BeforeSendMetric func(metric *Metric) *Metric
	// 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
	// when MaxBreadcrumbs is negative then ignore breadcrumbs.
	MaxBreadcrumbs int
	// Maximum number of spans.
	//
	// See https://develop.sentry.dev/sdk/envelopes/#size-limits for size limits
	// applied during event ingestion. Events that exceed these limits might get dropped.
	MaxSpans 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
	// MaxErrorDepth is the maximum number of errors reported in a chain of errors.
	// This protects the SDK from an arbitrarily long chain of wrapped errors.
	//
	// An additional consideration is that arguably reporting a long chain of errors
	// is of little use when debugging production errors with Sentry. The Sentry UI
	// is not optimized for long chains either. The top-level error together with a
	// stack trace is often the most useful information.
	MaxErrorDepth int
	// Default event tags. These are overridden by tags set on a scope.
	Tags map[string]string
	// DisableClientReports controls when client reports should be emitted.
	DisableClientReports bool
	// TraceIgnoreStatusCodes is a list of HTTP status codes that should not be traced.
	// Each element can be either:
	// - A single-element slice [code] for a specific status code
	// - A two-element slice [min, max] for a range of status codes (inclusive)
	// When an HTTP request results in a status code that matches any of these codes or ranges,
	// the transaction will not be sent to Sentry.
	//
	// Examples:
	//   [][]int{{404}}                           // ignore only status code 404
	//   [][]int{{400, 405}}                     // ignore status codes 400-405
	//   [][]int{{404}, {500}}                   // ignore status codes 404 and 500
	//   [][]int{{404}, {400, 405}, {500, 599}}  // ignore 404, range 400-405, and range 500-599
	//
	// By default, this ignores 404 status codes.
	//
	// IMPORTANT: to not ignore any status codes, the option should be an empty slice and not nil. The nil option is
	// used for defaulting to 404 ignores.
	TraceIgnoreStatusCodes [][]int
	// contains filtered or unexported fields
}

ClientOptions that configures a SDK Client.

type CollectionMode added in v0.48.0

type CollectionMode int

CollectionMode controls how key-value data (headers, cookies, query params) is collected.

Defaults to CollectionDenyList.

const (
	// CollectionDenyList keeps all keys and filters denied values.
	CollectionDenyList CollectionMode = iota

	// CollectionOff disables collection of the category entirely.
	CollectionOff

	// CollectionAllowList keeps all keys and sends real values only for allowed keys.
	CollectionAllowList
)

type Context added in v0.14.0

type Context = map[string]interface{}

type DataCollection added in v0.48.0

type DataCollection struct {
	// UserInfo controls automatic population of user.* fields from auto-instrumentation.
	//
	// This does NOT gate data explicitly set via Scope.SetUser(); that is
	// always attached. Defaults to true.
	UserInfo Option[bool]

	// Cookies configures collection of HTTP cookies.
	//
	// Defaults to using the built-in DenyList.
	Cookies *KeyValueCollectionBehavior

	// HTTPHeaders configures collection of HTTP request and response headers
	// independently.
	//
	// Defaults to both request and response using the built-in DenyList.
	HTTPHeaders *HeaderCollectionConfig

	// HTTPBodies controls which HTTP body types are collected.
	//
	// Defaults to collecting all valid body types.
	HTTPBodies []BodyType

	// QueryParams configures collection of URL query parameters.
	//
	// Defaults to using the built-in DenyList.
	QueryParams *KeyValueCollectionBehavior
	// contains filtered or unexported fields
}

DataCollection configures what data the SDK collects automatically. All fields are optional. nil or zero-value fields use the documented defaults, which collect rich context for debugging while scrubbing sensitive values via a built-in denylist.

See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection

func (*DataCollection) CollectCookies added in v0.48.0

func (dc *DataCollection) CollectCookies() bool

CollectCookies reports whether cookies should be collected.

func (*DataCollection) CollectHTTPBody added in v0.48.0

func (dc *DataCollection) CollectHTTPBody(bt BodyType) bool

CollectHTTPBody reports whether the given body type should be collected.

func (DataCollection) CollectQueryParams added in v0.48.0

func (dc DataCollection) CollectQueryParams() bool

CollectQueryParams reports whether query parameters should be collected.

func (DataCollection) FilterCookies added in v0.48.0

func (dc DataCollection) FilterCookies(values []string) string

FilterCookies applies the configured cookie collection behavior.

func (DataCollection) FilterHTTPBody added in v0.48.0

func (dc DataCollection) FilterHTTPBody(body []byte, contentType string) string

FilterHTTPBody applies sensitive-key filtering to parseable HTTP body data. Opaque raw bodies are replaced entirely.

func (DataCollection) FilterQueryString added in v0.48.0

func (dc DataCollection) FilterQueryString(rawQuery string) string

FilterQueryString applies the configured query-parameter collection behavior.

func (DataCollection) FilterRequestHeaders added in v0.48.0

func (dc DataCollection) FilterRequestHeaders(headers map[string]string) map[string]string

FilterRequestHeaders applies the configured request-header collection behavior.

func (DataCollection) FilterResponseHeaders added in v0.48.0

func (dc DataCollection) FilterResponseHeaders(headers map[string]string) map[string]string

FilterResponseHeaders applies the configured response-header collection behavior.

func (DataCollection) FilterSetCookies added in v0.48.0

func (dc DataCollection) FilterSetCookies(values []string) string

FilterSetCookies applies the configured cookie collection behavior to Set-Cookie header values.

func (DataCollection) FilterURL added in v0.48.0

func (dc DataCollection) FilterURL(u *url.URL) string

FilterURL applies query-parameter filtering to u and returns its redacted string form.

type DebugMeta added in v0.20.0

type DebugMeta struct {
	SdkInfo *DebugMetaSdkInfo `json:"sdk_info,omitempty"`
	Images  []DebugMetaImage  `json:"images,omitempty"`
}

The DebugMeta interface is not used in Golang apps, but may be populated when proxying Events from other platforms, like iOS, Android, and the Web. (See: https://develop.sentry.dev/sdk/event-payloads/debugmeta/ ).

type DebugMetaImage added in v0.20.0

type DebugMetaImage struct {
	Type        string `json:"type,omitempty"`         // all
	ImageAddr   string `json:"image_addr,omitempty"`   // macho,elf,pe
	ImageSize   int    `json:"image_size,omitempty"`   // macho,elf,pe
	DebugID     string `json:"debug_id,omitempty"`     // macho,elf,pe,wasm,sourcemap
	DebugFile   string `json:"debug_file,omitempty"`   // macho,elf,pe,wasm
	CodeID      string `json:"code_id,omitempty"`      // macho,elf,pe,wasm
	CodeFile    string `json:"code_file,omitempty"`    // macho,elf,pe,wasm,sourcemap
	ImageVmaddr string `json:"image_vmaddr,omitempty"` // macho,elf,pe
	Arch        string `json:"arch,omitempty"`         // macho,elf,pe
	UUID        string `json:"uuid,omitempty"`         // proguard
}

type DebugMetaSdkInfo added in v0.20.0

type DebugMetaSdkInfo struct {
	SdkName           string `json:"sdk_name,omitempty"`
	VersionMajor      int    `json:"version_major,omitempty"`
	VersionMinor      int    `json:"version_minor,omitempty"`
	VersionPatchlevel int    `json:"version_patchlevel,omitempty"`
}

type Dsn

type Dsn struct {
	protocol.Dsn
}

Dsn is used as the remote address source to client transport.

func NewDsn

func NewDsn(rawURL string) (*Dsn, error)

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) RequestHeaders deprecated

func (dsn Dsn) RequestHeaders() map[string]string

RequestHeaders returns all the necessary headers that have to be used in the transport when sending events to the /store endpoint.

Deprecated: This method shall only be used if you want to implement your own transport that sends events to the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate against the /envelope endpoint are added automatically.

type DsnParseError

type DsnParseError = protocol.DsnParseError

DsnParseError represents an error that occurs if a Sentry DSN cannot be parsed.

type DynamicSamplingContext added in v0.16.0

type DynamicSamplingContext struct {
	Entries map[string]string
	Frozen  bool
}

DynamicSamplingContext holds information about the current event that can be used to make dynamic sampling decisions.

func DynamicSamplingContextFromHeader added in v0.16.0

func DynamicSamplingContextFromHeader(header []byte) (DynamicSamplingContext, error)

func DynamicSamplingContextFromScope added in v0.29.0

func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext

DynamicSamplingContextFromScope returns the scope's propagation DSC. It is safe for concurrent use and freezes an unfrozen scope DSC on first use.

func DynamicSamplingContextFromTransaction added in v0.16.0

func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext

func (DynamicSamplingContext) HasEntries added in v0.16.0

func (d DynamicSamplingContext) HasEntries() bool

func (DynamicSamplingContext) IsFrozen added in v0.16.0

func (d DynamicSamplingContext) IsFrozen() bool

func (DynamicSamplingContext) String added in v0.16.0

func (d DynamicSamplingContext) String() string

type Event

type Event struct {
	Breadcrumbs []*Breadcrumb      `json:"breadcrumbs,omitempty"`
	Contexts    map[string]Context `json:"contexts,omitempty"`
	Dist        string             `json:"dist,omitempty"`
	Environment string             `json:"environment,omitempty"`
	EventID     EventID            `json:"event_id,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,omitzero"`
	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"`
	DebugMeta   *DebugMeta         `json:"debug_meta,omitempty"`
	Attachments []*Attachment      `json:"-"`

	Type            string           `json:"type,omitempty"`
	StartTime       time.Time        `json:"start_timestamp,omitzero"`
	Spans           []*Span          `json:"spans,omitempty"`
	TransactionInfo *TransactionInfo `json:"transaction_info,omitempty"`

	CheckIn       *CheckIn       `json:"check_in,omitempty"`
	MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"`

	// The fields below are only relevant for logs
	Logs []Log `json:"-"`

	// The fields below are only relevant for metrics
	Metrics []Metric `json:"-"`
	// contains filtered or unexported fields
}

Event is the fundamental data structure that is sent to Sentry.

func NewEvent

func NewEvent() *Event

NewEvent creates a new Event.

func (*Event) GetCategory added in v0.38.0

func (e *Event) GetCategory() ratelimit.Category

GetCategory returns the rate limit category for this event.

func (*Event) GetDynamicSamplingContext added in v0.38.0

func (e *Event) GetDynamicSamplingContext() map[string]string

GetDynamicSamplingContext returns trace context for the envelope header.

func (*Event) GetEventID added in v0.38.0

func (e *Event) GetEventID() string

GetEventID returns the event ID.

func (*Event) GetLogByteSize added in v0.44.0

func (e *Event) GetLogByteSize() int

GetLogByteSize returns the approximate total byte size of all logs in the event. It is used for client reports. Returns 0 for non-log events.

func (*Event) GetSdkInfo added in v0.38.0

func (e *Event) GetSdkInfo() *protocol.SdkInfo

GetSdkInfo returns SDK information for the envelope header.

func (*Event) GetSpanCount added in v0.44.0

func (e *Event) GetSpanCount() int

GetSpanCount returns the number of spans in the transaction including the transaction itself. It is used for client reports. Returns 0 for non-transaction events.

func (*Event) MakeSerializationSafe added in v0.44.0

func (e *Event) MakeSerializationSafe()

MakeSerializationSafe pre-serializes all fields containing user mutable data to json.RawMessage, preventing race conditions when the event is later serialized on a background goroutine.

func (*Event) MarshalJSON added in v0.6.0

func (e *Event) MarshalJSON() ([]byte, error)

MarshalJSON converts the Event struct to JSON.

func (*Event) SetException added in v0.21.0

func (e *Event) SetException(exception error, maxErrorDepth int)

SetException appends the unwrapped errors to the event's exception list.

maxErrorDepth is the maximum depth of the error chain we will look into while unwrapping the errors. If maxErrorDepth is -1, we will unwrap all errors in the chain.

func (*Event) ToEnvelope added in v0.36.2

func (e *Event) ToEnvelope(header *protocol.EnvelopeHeader) (*protocol.Envelope, error)

ToEnvelope converts the Event to a Sentry envelope.

func (*Event) ToEnvelopeItem added in v0.38.0

func (e *Event) ToEnvelopeItem() (item *protocol.EnvelopeItem, err error)

ToEnvelopeItem converts the Event to a Sentry envelope item.

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 CaptureCheckIn added in v0.23.0

func CaptureCheckIn(
	ctx context.Context,
	checkIn *CheckIn,
	monitorConfig *MonitorConfig,
	options ...CaptureOption,
) *EventID

CaptureCheckIn captures a (cron) monitor check-in using the scope and client carried by ctx.

func CaptureEvent

func CaptureEvent(ctx context.Context, event *Event, options ...CaptureOption) *EventID

CaptureEvent captures an event using the scope and client carried by ctx.

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

func CaptureException(ctx context.Context, exception error, options ...CaptureOption) *EventID

CaptureException captures an error using the scope and client carried by ctx.

func CaptureMessage

func CaptureMessage(ctx context.Context, message string, options ...CaptureOption) *EventID

CaptureMessage captures an arbitrary message using the scope and client carried by ctx.

func LastEventID

func LastEventID(ctx context.Context) EventID

LastEventID returns the last event ID captured in ctx's scope, or an empty ID when ctx does not carry one.

func Recover

func Recover(ctx context.Context, recovered any, options ...CaptureOption) *EventID

Recover captures a recovered panic value using the scope and client carried by ctx. When recovered is nil, Recover invokes Go's built-in recover and must itself be deferred.

type EventProcessor

type EventProcessor func(event *Event, hint *EventHint) *Event

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   uint64      `json:"thread_id,omitempty"`
	Stacktrace *Stacktrace `json:"stacktrace,omitempty"`
	Mechanism  *Mechanism  `json:"mechanism,omitempty"`
}

Exception specifies an error that occurred.

type Frame

type Frame struct {
	Function string `json:"function,omitempty"`
	Symbol   string `json:"symbol,omitempty"`
	// Module is, despite the name, the Sentry protocol equivalent of a Go
	// package's import path.
	Module      string                 `json:"module,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"`
	Vars        map[string]interface{} `json:"vars,omitempty"`
	// Package and the below are not used for Go stack trace frames.  In
	// other platforms it refers to a container where the Module can be
	// found.  For example, a Java JAR, a .NET Assembly, or a native
	// dynamic library.  They exists for completeness, allowing the
	// construction and reporting of custom event payloads.
	Package         string `json:"package,omitempty"`
	InstructionAddr string `json:"instruction_addr,omitempty"`
	AddrMode        string `json:"addr_mode,omitempty"`
	SymbolAddr      string `json:"symbol_addr,omitempty"`
	ImageAddr       string `json:"image_addr,omitempty"`
	Platform        string `json:"platform,omitempty"`
	StackStart      bool   `json:"stack_start,omitempty"`
}

Frame represents a function call and it's metadata. Frames are associated with a Stacktrace.

func NewFrame

func NewFrame(f runtime.Frame) Frame

NewFrame assembles a stacktrace frame out of runtime.Frame.

type HTTPSyncTransport

type HTTPSyncTransport struct {
	Timeout time.Duration
	// contains filtered or unexported fields
}

HTTPSyncTransport is a blocking implementation of Transport.

Clients using this transport will send requests to Sentry 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 creates a blocking HTTP transport.

func (*HTTPSyncTransport) Close added in v0.31.0

func (t *HTTPSyncTransport) Close()

Close cancels in-flight requests and rejects later sends.

func (*HTTPSyncTransport) Configure

func (t *HTTPSyncTransport) Configure(options ClientOptions)

Configure initializes the transport with the client's options before use.

func (*HTTPSyncTransport) FlushWithContext added in v0.34.0

func (t *HTTPSyncTransport) FlushWithContext(ctx context.Context) bool

FlushWithContext reports whether ctx is still live.

Sends block on the sync transport, so when ctx deadline is reached, it indicates that Flush did not succeed.

func (*HTTPSyncTransport) SendEnvelope

func (t *HTTPSyncTransport) SendEnvelope(ctx context.Context, envelope *protocol.Envelope) error

type HTTPTransport

type HTTPTransport struct {

	// Size of the transport buffer, in envelopes. Defaults to 1000.
	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 queue 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 creates an asynchronous HTTP transport with a bounded queue. NewClient configures it before use.

func (*HTTPTransport) Close added in v0.31.0

func (t *HTTPTransport) Close()

func (*HTTPTransport) Configure

func (t *HTTPTransport) Configure(options ClientOptions)

Configure initializes the transport with the client's options before use.

func (*HTTPTransport) FlushWithContext added in v0.34.0

func (t *HTTPTransport) FlushWithContext(ctx context.Context) bool

func (*HTTPTransport) SendEnvelope

func (t *HTTPTransport) SendEnvelope(_ context.Context, envelope *protocol.Envelope) error

SendEnvelope enqueues envelope without waiting for queue space.

type HeaderCollectionConfig added in v0.48.0

type HeaderCollectionConfig struct {
	// Request configures collection of HTTP request headers.
	Request *KeyValueCollectionBehavior
	// Response configures collection of HTTP response headers.
	Response *KeyValueCollectionBehavior
}

HeaderCollectionConfig configures how HTTP headers are collected for requests and responses independently.

type Integration

type Integration interface {
	Name() string
	SetupOnce(client *Client)
}

Integration allows for registering a functions that modify or discard captured events.

type KeyValueCollectionBehavior added in v0.48.0

type KeyValueCollectionBehavior struct {
	// Mode controls the collection strategy.
	Mode CollectionMode
	// Terms is a list of additional terms used by the active mode.
	Terms []string
}

KeyValueCollectionBehavior configures how key-value data is collected and filtered.

type Level

type Level string

Level marks the severity of the event.

const (
	LevelDebug   Level = "debug"
	LevelInfo    Level = "info"
	LevelWarning Level = "warning"
	LevelError   Level = "error"
	LevelFatal   Level = "fatal"
)

Describes the severity of the event.

type Log added in v0.33.0

type Log struct {
	Timestamp  time.Time                  `json:"timestamp,omitzero"`
	TraceID    TraceID                    `json:"trace_id"`
	SpanID     SpanID                     `json:"span_id,omitzero"`
	Level      LogLevel                   `json:"level"`
	Severity   int                        `json:"severity_number,omitempty"`
	Body       string                     `json:"body"`
	Attributes map[string]attribute.Value `json:"attributes,omitempty"`
	// contains filtered or unexported fields
}

func (*Log) ApproximateSize added in v0.44.0

func (l *Log) ApproximateSize() int

ApproximateSize returns the pre-computed approximate serialized size in bytes.

func (*Log) GetCategory added in v0.38.0

func (l *Log) GetCategory() ratelimit.Category

GetCategory returns the rate limit category for logs.

func (*Log) MakeSerializationSafe added in v0.44.0

func (l *Log) MakeSerializationSafe()

MakeSerializationSafe is a no-op for Log, all fields are passed from the safe attribute API.

type LogEntry added in v0.35.0

type LogEntry interface {
	// WithCtx creates a new LogEntry with the specified context without overwriting the previous one.
	WithCtx(ctx context.Context) LogEntry
	// StringSlice adds a string slice attribute to the LogEntry.
	StringSlice(key string, value []string) LogEntry
	// String adds a string attribute to the LogEntry.
	String(key, value string) LogEntry
	// Int adds an int attribute to the LogEntry.
	Int(key string, value int) LogEntry
	// Int64Slice adds an int64 slice attribute to the LogEntry.
	Int64Slice(key string, value []int64) LogEntry
	// Int64 adds an int64 attribute to the LogEntry.
	Int64(key string, value int64) LogEntry
	// Float64Slice adds a float64 slice attribute to the LogEntry.
	Float64Slice(key string, value []float64) LogEntry
	// Float64 adds a float64 attribute to the LogEntry.
	Float64(key string, value float64) LogEntry
	// BoolSlice adds a bool slice attribute to the LogEntry.
	BoolSlice(key string, value []bool) LogEntry
	// Bool adds a bool attribute to the LogEntry.
	Bool(key string, value bool) LogEntry
	// Emit emits the LogEntry with the provided arguments.
	Emit(args ...interface{})
	// Emitf emits the LogEntry using a format string and arguments.
	Emitf(format string, args ...interface{})
}

LogEntry defines the interface for a log entry that supports chaining attributes.

type LogLevel added in v0.33.0

type LogLevel string
const (
	LogLevelTrace LogLevel = "trace"
	LogLevelDebug LogLevel = "debug"
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
	LogLevelError LogLevel = "error"
	LogLevelFatal LogLevel = "fatal"
)

type Logger

type Logger interface {
	// Write implements the io.Writer interface using the context passed to NewLogger.
	Write(p []byte) (n int, err error)

	// SetAttributes allows attaching parameters to the logger using the attribute API.
	// These attributes will be included in all subsequent log entries.
	SetAttributes(...attribute.Builder)

	// Trace defines the [sentry.LogLevel] for the log entry.
	Trace() LogEntry
	// Debug defines the [sentry.LogLevel] for the log entry.
	Debug() LogEntry
	// Info defines the [sentry.LogLevel] for the log entry.
	Info() LogEntry
	// Warn defines the [sentry.LogLevel] for the log entry.
	Warn() LogEntry
	// Error defines the [sentry.LogLevel] for the log entry.
	Error() LogEntry
	// Fatal defines the [sentry.LogLevel] for the log entry.
	Fatal() LogEntry
	// Panic defines the [sentry.LogLevel] for the log entry.
	Panic() LogEntry
	// LFatal defines the [sentry.LogLevel] for the log entry. This only sets
	// the level to fatal, but does not panic or exit.
	LFatal() LogEntry
	// GetCtx returns the [context.Context] set on the logger.
	GetCtx() context.Context
}

Logger provides a chaining API for structured logging to Sentry.

func NewLogger added in v0.33.0

func NewLogger(ctx context.Context) Logger

NewLogger returns a Logger that emits logs to Sentry.

type Mechanism added in v0.19.0

type Mechanism struct {
	Type             string         `json:"type"`
	Description      string         `json:"description,omitempty"`
	HelpLink         string         `json:"help_link,omitempty"`
	Source           string         `json:"source,omitempty"`
	Handled          *bool          `json:"handled,omitempty"`
	ParentID         *int           `json:"parent_id,omitempty"`
	ExceptionID      int            `json:"exception_id"`
	IsExceptionGroup bool           `json:"is_exception_group,omitempty"`
	Data             map[string]any `json:"data,omitempty"`
}

Mechanism is the mechanism by which an exception was generated and handled.

func (*Mechanism) SetUnhandled added in v0.19.0

func (m *Mechanism) SetUnhandled()

SetUnhandled indicates that the exception is an unhandled exception, i.e. from a panic.

type Meter added in v0.42.0

type Meter interface {
	// WithCtx returns a new Meter that uses the given context for trace/span association.
	WithCtx(ctx context.Context) Meter
	// SetAttributes allows attaching parameters to the meter using the attribute API.
	// These attributes will be included in all subsequent metrics.
	SetAttributes(attrs ...attribute.Builder)
	// Count records a count metric.
	Count(name string, count int64, opts ...MeterOption)
	// Gauge records a gauge metric.
	Gauge(name string, value float64, opts ...MeterOption)
	// Distribution records a distribution metric.
	Distribution(name string, sample float64, opts ...MeterOption)
}

Meter provides an interface for recording metrics.

func NewMeter added in v0.42.0

func NewMeter(ctx context.Context) Meter

NewMeter returns a new Meter.

type MeterOption added in v0.42.0

type MeterOption func(*meterOptions)

MeterOption configures a metric recording call.

func WithAttributes added in v0.42.0

func WithAttributes(attrs ...attribute.Builder) MeterOption

WithAttributes sets attributes for the metric.

func WithUnit added in v0.42.0

func WithUnit(unit string) MeterOption

WithUnit sets the unit for the metric (e.g., "millisecond", "byte").

type Metric added in v0.28.0

type Metric struct {
	Timestamp  time.Time                  `json:"timestamp,omitzero"`
	TraceID    TraceID                    `json:"trace_id"`
	SpanID     SpanID                     `json:"span_id,omitzero"`
	Type       MetricType                 `json:"type"`
	Name       string                     `json:"name"`
	Value      MetricValue                `json:"value"`
	Unit       string                     `json:"unit,omitempty"`
	Attributes map[string]attribute.Value `json:"attributes,omitempty"`
}

func (*Metric) GetCategory added in v0.42.0

func (m *Metric) GetCategory() ratelimit.Category

GetCategory returns the rate limit category for metrics.

func (*Metric) MakeSerializationSafe added in v0.44.0

func (m *Metric) MakeSerializationSafe()

MakeSerializationSafe is a no-op for Metric, all fields are passed from the safe attribute API.

type MetricType added in v0.42.0

type MetricType string
const (
	MetricTypeInvalid      MetricType = ""
	MetricTypeCounter      MetricType = "counter"
	MetricTypeGauge        MetricType = "gauge"
	MetricTypeDistribution MetricType = "distribution"
)

type MetricValue added in v0.42.0

type MetricValue struct {
	// contains filtered or unexported fields
}

MetricValue stores metric values with full precision. It supports int64 (for counters) and float64 (for gauges and distributions).

func Float64MetricValue added in v0.42.0

func Float64MetricValue(v float64) MetricValue

Float64MetricValue creates a MetricValue from a float64. Used for gauge and distribution metrics.

func Int64MetricValue added in v0.42.0

func Int64MetricValue(v int64) MetricValue

Int64MetricValue creates a MetricValue from an int64. Used for counter metrics to preserve full int64 precision.

func (MetricValue) AsInterface added in v0.42.0

func (v MetricValue) AsInterface() any

AsInterface returns the value as int64 or float64. Use type assertion or type switch to handle the result.

func (MetricValue) Float64 added in v0.42.0

func (v MetricValue) Float64() (float64, bool)

Float64 returns the value as float64 if it holds a float64. The second return value indicates whether the type matched.

func (MetricValue) Int64 added in v0.42.0

func (v MetricValue) Int64() (int64, bool)

Int64 returns the value as int64 if it holds an int64. The second return value indicates whether the type matched.

func (MetricValue) MarshalJSON added in v0.42.0

func (v MetricValue) MarshalJSON() ([]byte, error)

MarshalJSON serializes the value as a bare number.

func (MetricValue) Type added in v0.42.0

func (v MetricValue) Type() attribute.Type

Type returns the type of the stored value (attribute.INT64 or attribute.FLOAT64).

type MockLogEntry added in v0.43.0

type MockLogEntry struct {
	Attributes map[string]any
}

MockLogEntry implements sentry.LogEntry for use in tests.

func NewMockLogEntry added in v0.43.0

func NewMockLogEntry() *MockLogEntry

func (*MockLogEntry) Bool added in v0.43.0

func (m *MockLogEntry) Bool(key string, value bool) LogEntry

func (*MockLogEntry) BoolSlice added in v0.44.0

func (m *MockLogEntry) BoolSlice(key string, value []bool) LogEntry

func (*MockLogEntry) Emit added in v0.43.0

func (m *MockLogEntry) Emit(...any)

func (*MockLogEntry) Emitf added in v0.43.0

func (m *MockLogEntry) Emitf(string, ...any)

func (*MockLogEntry) Float64 added in v0.43.0

func (m *MockLogEntry) Float64(key string, value float64) LogEntry

func (*MockLogEntry) Float64Slice added in v0.44.0

func (m *MockLogEntry) Float64Slice(key string, value []float64) LogEntry

func (*MockLogEntry) Int added in v0.43.0

func (m *MockLogEntry) Int(key string, value int) LogEntry

func (*MockLogEntry) Int64 added in v0.43.0

func (m *MockLogEntry) Int64(key string, value int64) LogEntry

func (*MockLogEntry) Int64Slice added in v0.44.0

func (m *MockLogEntry) Int64Slice(key string, value []int64) LogEntry

func (*MockLogEntry) String added in v0.43.0

func (m *MockLogEntry) String(key, value string) LogEntry

func (*MockLogEntry) StringSlice added in v0.44.0

func (m *MockLogEntry) StringSlice(key string, value []string) LogEntry

func (*MockLogEntry) WithCtx added in v0.43.0

func (m *MockLogEntry) WithCtx(_ context.Context) LogEntry

type MockTransport added in v0.32.0

type MockTransport struct {
	// contains filtered or unexported fields
}

MockTransport implements Transport for use in tests.

func (*MockTransport) Close added in v0.32.0

func (t *MockTransport) Close()

func (*MockTransport) Configure added in v0.32.0

func (t *MockTransport) Configure(options ClientOptions)

Configure marks delivery as synchronous so captured events are visible immediately.

func (*MockTransport) Events added in v0.32.0

func (t *MockTransport) Events() []*Event

Events returns captured telemetry decoded from the wire format. Logs and metrics are represented by one Event per batch; client reports are omitted. Values in context and extra maps have JSON types, not their original Go types.

func (*MockTransport) FlushWithContext added in v0.34.0

func (t *MockTransport) FlushWithContext(_ context.Context) bool

func (*MockTransport) SendEnvelope

func (t *MockTransport) SendEnvelope(_ context.Context, envelope *protocol.Envelope) error

SendEnvelope captures an envelope and decodes its events for assertions.

type MonitorConfig added in v0.23.0

type MonitorConfig struct {
	Schedule MonitorSchedule `json:"schedule,omitempty"`
	// The allowed margin of minutes after the expected check-in time that
	// the monitor will not be considered missed for.
	CheckInMargin int64 `json:"checkin_margin,omitempty"`
	// The allowed duration in minutes that the monitor may be `in_progress`
	// for before being considered failed due to timeout.
	MaxRuntime int64 `json:"max_runtime,omitempty"`
	// A tz database string representing the timezone which the monitor's execution schedule is in.
	// See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
	Timezone string `json:"timezone,omitempty"`
	// The number of consecutive failed check-ins it takes before an issue is created.
	FailureIssueThreshold int64 `json:"failure_issue_threshold,omitempty"`
	// The number of consecutive OK check-ins it takes before an issue is resolved.
	RecoveryThreshold int64 `json:"recovery_threshold,omitempty"`
}

type MonitorSchedule added in v0.23.0

type MonitorSchedule interface {
	// contains filtered or unexported methods
}

func CrontabSchedule added in v0.23.0

func CrontabSchedule(scheduleString string) MonitorSchedule

CrontabSchedule defines the MonitorSchedule with a cron format. Example: "8 * * * *".

func IntervalSchedule added in v0.23.0

func IntervalSchedule(value int64, unit MonitorScheduleUnit) MonitorSchedule

IntervalSchedule defines the MonitorSchedule with an interval format.

Example:

IntervalSchedule(1, sentry.MonitorScheduleUnitDay)

type MonitorScheduleUnit added in v0.23.0

type MonitorScheduleUnit string
const (
	MonitorScheduleUnitMinute MonitorScheduleUnit = "minute"
	MonitorScheduleUnitHour   MonitorScheduleUnit = "hour"
	MonitorScheduleUnitDay    MonitorScheduleUnit = "day"
	MonitorScheduleUnitWeek   MonitorScheduleUnit = "week"
	MonitorScheduleUnitMonth  MonitorScheduleUnit = "month"
	MonitorScheduleUnitYear   MonitorScheduleUnit = "year"
)

type NoopTransport

type NoopTransport struct{}

NoopTransport is a transport implementation that drops all events. Used internally when an empty or invalid DSN is provided.

func NewNoopTransport

func NewNoopTransport() *NoopTransport

func (*NoopTransport) Close

func (t *NoopTransport) Close()

func (*NoopTransport) Configure

func (t *NoopTransport) Configure(_ ClientOptions)

func (*NoopTransport) FlushWithContext

func (t *NoopTransport) FlushWithContext(_ context.Context) bool

func (*NoopTransport) SendEnvelope

func (t *NoopTransport) SendEnvelope(_ context.Context, _ *protocol.Envelope) error

type Option added in v0.48.0

type Option[T any] struct {
	Value T
	IsSet bool
}

Option represents an optional configuration value.

The zero value is unset. Use Set to distinguish an explicitly configured zero value, such as false, 0, or "", from an unset option.

func Set added in v0.48.0

func Set[T any](v T) Option[T]

Set returns an Option containing v.

func (Option[T]) Or added in v0.48.0

func (o Option[T]) Or(defaultValue T) T

Or returns the option value when set, or defaultValue otherwise.

type PropagationContext added in v0.29.0

type PropagationContext struct {
	TraceID                TraceID                `json:"trace_id"`
	SpanID                 SpanID                 `json:"span_id"`
	ParentSpanID           SpanID                 `json:"parent_span_id,omitzero"`
	Sampled                Sampled                `json:"-"`
	DynamicSamplingContext DynamicSamplingContext `json:"-"`
}

func NewPropagationContext added in v0.29.0

func NewPropagationContext() PropagationContext

func PropagationContextFromHeaders added in v0.29.0

func PropagationContextFromHeaders(trace, baggage string) (PropagationContext, error)

PropagationContextFromHeaders extracts incoming trace and sampling metadata. Malformed baggage returns an error together with a usable propagation context; a valid sentry-trace header is retained with empty, frozen sampling metadata.

func (PropagationContext) Map added in v0.29.0

func (p PropagationContext) Map() map[string]interface{}

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 added in v0.6.0

func NewRequest(r *http.Request) *Request

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 SDKMetaData added in v0.16.0

type SDKMetaData struct {
	// contains filtered or unexported fields
}

SDKMetaData is a struct to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get send to Sentry.

type Sampled added in v0.9.0

type Sampled int8

Sampled signifies a sampling decision.

const (
	SampledFalse     Sampled = -1
	SampledUndefined Sampled = 0
	SampledTrue      Sampled = 1
)

The possible trace sampling decisions are: SampledFalse, SampledUndefined (default) and SampledTrue.

func (Sampled) Bool added in v0.9.0

func (s Sampled) Bool() bool

Bool returns true if the sample decision is SampledTrue, false otherwise.

func (Sampled) String added in v0.9.0

func (s Sampled) String() string

type SamplingContext added in v0.9.0

type SamplingContext struct {
	Span   *Span // The current span, always non-nil.
	Parent *Span // The local parent span, non-nil only when the parent exists in the same process.
	// ParentSampled is the sampling decision of the parent span.
	//
	// For a remote span, Parent is nil but ParentSampled reflects the upstream decision.
	// For a local span, ParentSampled mirrors Parent.Sampled.
	ParentSampled Sampled
	// ParentSampleRate is the sample rate used by the parent transaction.
	ParentSampleRate *float64
}

A SamplingContext is passed to a TracesSampler to determine a sampling decision.

TODO(tracing): possibly expand SamplingContext to include custom / user-provided data.

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

Scope holds contextual data for an operation.

The scope is an object that can be cloned efficiently and stores data that is locally relevant to an event.

func GlobalScope

func GlobalScope() *Scope

GlobalScope returns the process-wide global scope.

func NewScope

func NewScope() *Scope

NewScope creates a new Scope.

func ScopeFromContext

func ScopeFromContext(ctx context.Context) *Scope

ScopeFromContext returns the scope carried by ctx, or nil when there is none.

func WithScope

func WithScope(ctx context.Context) (context.Context, *Scope)

WithScope returns a derived context and a forked scope. It clones a carried scope, or starts an empty scope with a new propagation context when ctx does not carry one.

func (*Scope) AddAttachment added in v0.23.0

func (scope *Scope) AddAttachment(attachment *Attachment)

AddAttachment adds new attachment to the current scope.

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

func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event

ApplyToEvent takes the data from the current scope and attaches it to the event.

func (*Scope) Clear

func (scope *Scope) Clear()

Clear removes enrichment data while preserving event processors, trace correlation, and the last event ID. It is safe for concurrent use.

func (*Scope) ClearAttachments added in v0.23.0

func (scope *Scope) ClearAttachments()

ClearAttachments clears all attachments from the current scope.

func (*Scope) ClearBreadcrumbs

func (scope *Scope) ClearBreadcrumbs()

ClearBreadcrumbs clears all breadcrumbs from the current scope.

func (*Scope) Clone

func (scope *Scope) Clone() *Scope

Clone returns a copy of the current scope without its last event ID.

func (*Scope) RemoveAttribute added in v0.44.0

func (scope *Scope) RemoveAttribute(key string)

RemoveAttribute removes an attribute from the current scope.

func (*Scope) RemoveContext

func (scope *Scope) RemoveContext(key string)

RemoveContext removes a context from the current scope.

func (*Scope) RemoveTag

func (scope *Scope) RemoveTag(key string)

RemoveTag removes a tag from the current scope.

func (*Scope) SetAttributes added in v0.44.0

func (scope *Scope) SetAttributes(attrs ...attribute.Builder)

SetAttributes adds attributes to the current scope.

func (*Scope) SetContext

func (scope *Scope) SetContext(key string, value Context)

SetContext adds a context to the current scope.

func (*Scope) SetContexts

func (scope *Scope) SetContexts(contexts map[string]Context)

SetContexts assigns multiple contexts to the current scope.

func (*Scope) SetFingerprint

func (scope *Scope) SetFingerprint(fingerprint []string)

SetFingerprint sets new fingerprint for the current scope.

func (*Scope) SetLevel

func (scope *Scope) SetLevel(level Level)

SetLevel sets new level for the current scope.

func (*Scope) SetPropagationContext added in v0.29.0

func (scope *Scope) SetPropagationContext(propagationContext PropagationContext)

SetPropagationContext sets the propagation context for the current scope.

func (*Scope) SetRequest

func (scope *Scope) SetRequest(r *http.Request)

SetRequest sets the request for the current scope.

func (*Scope) SetRequestBody added in v0.6.0

func (scope *Scope) SetRequestBody(b []byte)

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

func (scope *Scope) SetTag(key, value string)

SetTag adds a tag to the current scope.

func (*Scope) SetTags

func (scope *Scope) SetTags(tags map[string]string)

SetTags assigns multiple tags to the current scope.

func (*Scope) SetUser

func (scope *Scope) SetUser(user User)

SetUser sets the user for the current scope.

type SdkInfo

type SdkInfo = protocol.SdkInfo

SdkInfo contains all metadata about the SDK.

type SdkPackage

type SdkPackage = protocol.SdkPackage

type Span added in v0.7.0

type Span struct {
	TraceID      TraceID                `json:"trace_id"`
	SpanID       SpanID                 `json:"span_id"`
	ParentSpanID SpanID                 `json:"parent_span_id,omitzero"`
	Name         string                 `json:"name,omitempty"`
	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,omitzero"`
	EndTime      time.Time              `json:"timestamp,omitzero"`
	Data         map[string]interface{} `json:"data,omitempty"`
	Sampled      Sampled                `json:"-"`
	Source       TransactionSource      `json:"-"`
	Origin       SpanOrigin             `json:"origin,omitempty"`
	// 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 SpanFromContext added in v0.23.0

func SpanFromContext(ctx context.Context) *Span

SpanFromContext returns the last span stored in the context, or nil if no span is set on the context.

func StartSpan added in v0.9.0

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 StartTransaction added in v0.15.0

func StartTransaction(ctx context.Context, name string, options ...SpanOption) *Span

StartTransaction will create a transaction (root span) if there's no existing transaction in the context otherwise, it will return the existing transaction. An existing transaction is returned unchanged; options are ignored.

func TransactionFromContext added in v0.9.0

func TransactionFromContext(ctx context.Context) *Span

TransactionFromContext returns the root span of the current transaction. It returns nil if no transaction is tracked in the context.

func (*Span) Context added in v0.9.0

func (s *Span) Context() context.Context

Context returns the context containing the span.

func (*Span) Finish added in v0.9.0

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.

The logic is executed at most once per span, so that (incorrectly) calling it twice never double sends to Sentry.

func (*Span) GetTransaction added in v0.18.0

func (s *Span) GetTransaction() *Span

GetTransaction returns the transaction that contains this span.

For transaction spans it returns itself. For spans that were created manually the method returns "nil".

func (*Span) IsTransaction added in v0.18.0

func (s *Span) IsTransaction() bool

IsTransaction checks if the given span is a transaction.

func (*Span) MarshalJSON added in v0.9.0

func (s *Span) MarshalJSON() ([]byte, error)

MarshalJSON emits the span using pre-serialized fields if available.

func (*Span) SetContext added in v0.20.0

func (s *Span) SetContext(key string, value Context)

SetContext sets a context on the span. It is recommended to use SetContext instead of accessing the contexts map directly as SetContext takes care of initializing the map when necessary.

func (*Span) SetData added in v0.18.0

func (s *Span) SetData(name string, value interface{})

SetData sets a data on the span. It is recommended to use SetData instead of accessing the data map directly as SetData takes care of initializing the map when necessary.

func (*Span) SetDynamicSamplingContext added in v0.18.0

func (s *Span) SetDynamicSamplingContext(dsc DynamicSamplingContext)

SetDynamicSamplingContext sets the given dynamic sampling context on the current transaction. Once the DSC has been propagated or sent, it is frozen and later calls leave it unchanged. The supplied entries are copied.

func (*Span) SetTag added in v0.9.0

func (s *Span) SetTag(name, value string)

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 added in v0.9.0

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) ToBaggage added in v0.16.0

func (s *Span) ToBaggage() string

ToBaggage returns the serialized DynamicSamplingContext from a transaction. Use this function to propagate the DynamicSamplingContext to a downstream SDK, either as the value of the "baggage" HTTP header, or as an html "baggage" meta tag.

func (*Span) ToSentryTrace added in v0.9.0

func (s *Span) ToSentryTrace() string

ToSentryTrace returns the serialized TraceParentContext from a transaction/span. Use this function to propagate the TraceParentContext to a downstream SDK, either as the value of the "sentry-trace" HTTP header, or as an html "sentry-trace" meta tag.

func (*Span) ToTraceparent added in v0.41.0

func (s *Span) ToTraceparent() string

ToTraceparent returns the W3C traceparent header value for the span.

type SpanID added in v0.9.0

type SpanID [8]byte

SpanID identifies a span.

func (SpanID) Hex added in v0.9.0

func (id SpanID) Hex() []byte

func (SpanID) MarshalText added in v0.9.0

func (id SpanID) MarshalText() ([]byte, error)

func (SpanID) String added in v0.9.0

func (id SpanID) String() string

type SpanOption added in v0.9.0

type SpanOption func(s *Span)

A SpanOption is a function that can modify the properties of a span.

func ContinueFromHeaders added in v0.16.0

func ContinueFromHeaders(trace, baggage string) SpanOption

ContinueFromHeaders returns a span option that continues a trace from the sentry-trace and baggage header values.

func ContinueFromRequest added in v0.9.0

func ContinueFromRequest(r *http.Request) SpanOption

ContinueFromRequest returns a span option that continues a trace from r's sentry-trace and baggage headers. All baggage header values are combined.

func WithDescription added in v0.26.0

func WithDescription(description string) SpanOption

WithDescription sets the description of a span.

func WithOpName added in v0.21.0

func WithOpName(name string) SpanOption

WithOpName sets the operation name for a given span.

func WithSpanOrigin added in v0.29.0

func WithSpanOrigin(origin SpanOrigin) SpanOption

WithSpanOrigin sets the origin of the span.

func WithSpanSampled added in v0.21.0

func WithSpanSampled(sampled Sampled) SpanOption

WithSpanSampled updates the sampling flag for a given span.

func WithTransactionName added in v0.21.0

func WithTransactionName(name string) SpanOption

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

func WithTransactionSource added in v0.21.0

func WithTransactionSource(source TransactionSource) SpanOption

WithTransactionSource sets the source of the transaction name.

Note: if the transaction source is not a valid source (as described by the spec https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations), it will be corrected to "custom" eventually, before the transaction is sent.

type SpanOrigin added in v0.29.0

type SpanOrigin string

SpanOrigin indicates what created a trace or a span. See: https://develop.sentry.dev/sdk/performance/trace-origin/

type SpanStatus added in v0.9.0

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
	SpanStatusUnavailable
	SpanStatusDataLoss
	SpanStatusUnauthenticated
)

func HTTPtoSpanStatus added in v0.22.0

func HTTPtoSpanStatus(code int) SpanStatus

HTTPtoSpanStatus converts an HTTP status code to a SpanStatus.

func (SpanStatus) MarshalJSON added in v0.9.0

func (ss SpanStatus) MarshalJSON() ([]byte, error)

func (SpanStatus) String added in v0.9.0

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 added in v0.7.0

type TraceContext struct {
	TraceID      TraceID                `json:"trace_id"`
	SpanID       SpanID                 `json:"span_id"`
	ParentSpanID SpanID                 `json:"parent_span_id,omitzero"`
	Op           string                 `json:"op,omitempty"`
	Description  string                 `json:"description,omitempty"`
	Status       SpanStatus             `json:"status,omitempty"`
	Data         map[string]interface{} `json:"data,omitempty"`
}

A TraceContext carries information about an ongoing trace and is meant to be stored in Event.Contexts (as *TraceContext).

func (TraceContext) Map added in v0.14.0

func (tc TraceContext) Map() map[string]interface{}

type TraceID added in v0.9.0

type TraceID [16]byte

TraceID identifies a trace.

func (TraceID) Hex added in v0.9.0

func (id TraceID) Hex() []byte

func (TraceID) MarshalText added in v0.9.0

func (id TraceID) MarshalText() ([]byte, error)

func (TraceID) String added in v0.9.0

func (id TraceID) String() string

type TraceParentContext added in v0.18.0

type TraceParentContext struct {
	TraceID      TraceID
	ParentSpanID SpanID
	Sampled      Sampled
}

TraceParentContext describes the context of a (remote) parent span.

The context is normally extracted from a received "sentry-trace" header and used to initialize a new transaction.

Note: the name might be not the best one. It was taken mostly to stay aligned with other SDKs, and it alludes to W3C "traceparent" header (https://www.w3.org/TR/trace-context/), which serves a similar purpose to "sentry-trace". We should eventually consider making this type internal-only and give it a better name.

func ParseTraceParentContext added in v0.18.0

func ParseTraceParentContext(header []byte) (traceParentContext TraceParentContext, valid bool)

ParseTraceParentContext parses a sentry-trace header and builds a TraceParentContext from the parsed values. If the header was parsed correctly, the second returned argument ("valid") will be set to true, otherwise (e.g., empty or malformed header) it will be false.

type TracesSampler added in v0.9.0

type TracesSampler func(ctx SamplingContext) float64

The TracesSample type is an adapter to allow the use of ordinary functions as a TracesSampler.

func (TracesSampler) Sample added in v0.9.0

func (f TracesSampler) Sample(ctx SamplingContext) float64

type TransactionInfo added in v0.16.0

type TransactionInfo struct {
	Source TransactionSource `json:"source,omitempty"`
}

Contains information about how the name of the transaction was determined.

type TransactionSource added in v0.16.0

type TransactionSource string

Contains information about how the name of the transaction was determined.

const (
	SourceCustom    TransactionSource = "custom"
	SourceURL       TransactionSource = "url"
	SourceRoute     TransactionSource = "route"
	SourceView      TransactionSource = "view"
	SourceComponent TransactionSource = "component"
	SourceTask      TransactionSource = "task"
)

type Transport

type Transport interface {
	// Configure initializes the transport before use. NewClient calls it once
	// with resolved options; wrappers must forward it to their transport.
	Configure(options ClientOptions)
	// SendEnvelope returns an error only when rejecting an envelope. The caller
	// records rejected items; built-in transports record losses after acceptance.
	// A nil error does not guarantee delivery. Implementations must return
	// promptly once ctx is done.
	SendEnvelope(ctx context.Context, envelope *protocol.Envelope) error
	// FlushWithContext waits for pending delivery attempts until ctx is canceled.
	// It must return false if ctx is done before they complete, including
	// attempts that SendEnvelope made inline with the same ctx.
	FlushWithContext(ctx context.Context) bool
	// Close releases transport resources.
	Close()
}

Transport delivers envelopes prepared by the telemetry processor. Implementations may send immediately or enqueue envelopes for delivery and must be safe for concurrent use.

type User

type User struct {
	ID        string            `json:"id,omitempty"`
	Email     string            `json:"email,omitempty"`
	IPAddress string            `json:"ip_address,omitempty"`
	Username  string            `json:"username,omitempty"`
	Name      string            `json:"name,omitempty"`
	Data      map[string]string `json:"data,omitempty"`
}

User describes the user associated with an Event. If this is used, at least an ID or an IP address should be provided.

func (User) IsEmpty added in v0.15.0

func (u User) IsEmpty() bool

Directories

Path Synopsis
_examples
basic command
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.
crons command
echo command
fasthttp command
fiber command
flush command
gin command
grpc/client command
grpc/server command
http command
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.
httpclient command
iris command
logrus command
logs command
metrics command
multiclient command
negroni command
otlp command
This example demonstrates two ways to set up OpenTelemetry tracing with Sentry.
This example demonstrates two ways to set up OpenTelemetry tracing with Sentry.
recover command
recover-repanic command
This is an example program that demonstrates an advanced use of the Sentry SDK using context, 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 context, 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.
slog command
synctransport command
with_extra command
zap command
zerolog command
cron module
echo module
fasthttp module
fiber module
fiberv3 module
gin module
grpc module
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.
Package sentryhttpclient provides Sentry integration for Requests modules to enable distributed tracing between services.
Package sentryhttpclient provides Sentry integration for Requests modules to enable distributed tracing between services.
internal
contextkey
Package contextkey contains context keys shared with integration modules.
Package contextkey contains context keys shared with integration modules.
otel/baggage/internal/baggage
Package baggage provides base types and functionality to store and retrieve baggage in Go context.
Package baggage provides base types and functionality to store and retrieve baggage in Go context.
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.
sentrytest
Package sentrytest provides test fixtures for the Sentry Go SDK.
Package sentrytest provides test fixtures for the Sentry Go SDK.
iris module
logrus module
negroni module
otel module
otlp module
Package protocol defines Sentry's wire envelopes, DSNs, and SDK metadata.
Package protocol defines Sentry's wire envelopes, DSNs, and SDK metadata.
slog module
sql module
zap module
zerolog module

Jump to

Keyboard shortcuts

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