Categorygithub.com/tymate/sentry-go
modulepackage
2.0.1+incompatible
Repository: https://github.com/tymate/sentry-go.git
Documentation: pkg.go.dev

# README

sentry-go Build Status codecov

A robust Sentry client for Go applications

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

Features

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

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

Versions

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

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

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

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

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

Examples

Breadcrumbs and Exceptions

package main

import (
    "fmt"

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

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

    cl := sentry.NewClient()

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

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

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

HTTP Request Context

package main

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

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

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

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

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

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

        os.Exit(1)
    }
}

Advanced Use Cases

Custom SendQueues

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

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

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

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

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

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

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

# Functions

AddDefaultOptionProvider allows you to register a new default option which will be globally set on all top-level clients.
AddDefaultOptions allows you to configure options which will be globally set on all top-level clients by default.
AddInternalPrefixes allows you to easily add packages which will be considered "internal" in your stack traces.
Breadcrumbs can be included in your events to help track down the sequence of steps that resulted in a failure.
Context allows you to manually set a context entry by providing its key and the data to accompany it.
Culprit allows you to specify the name of the transaction (or culprit) which casued this event.
DefaultBreadcrumbs are registered for inclusion in situations where you have not specified your own Breadcrumbs collection.
DefaultClient is a singleton client instance which can be used instead of instantiating a new client manually.
DeviceContext allows you to set the context describing the device that your application is being executed on.
DSN lets you specify the unique Sentry DSN used to submit events for your application.
Environment allows you to configure the name of the environment you pass to Sentry with your event.
EventID is an option which controls the UUID used to represent an event.
Exception allows you to include the details of an exception which occurred within your application as part of the event you send to Sentry.
ExceptionForError allows you to include the details of an error which occurred within your application as part of the event you send to Sentry.
Extra allows you to provide additional arbitrary metadata with your event.
Fingerprint is used to configure the array of strings used to deduplicate events when they are processed by Sentry.
HTTP creates a new HTTP interface with the raw data provided by a user.
HTTPRequest passes the request context from a net/http request object to Sentry.
Level is used to set the severity level of an event before it is sent to Sentry.
Logger allows you to configure the hostname reported to Sentry with an event.
Message generates a new message entry for Sentry, optionally using a format string with standard fmt.Sprintf params.
Modules allows you to specify the versions of various modules used by your application.
NewBreadcrumbsList will create a new BreadcrumbsList which can be used to track breadcrumbs within a specific context.
NewClient will create a new client instance with the provided default options and config.
NewEventID attempts to generate a new random UUIDv4 event ID which can be passed to the EventID() option.
NewExceptionInfo creates a new ExceptionInfo object which can then be populated with information about an exception which occurred before being passed to the Exception() method for submission to Sentry.
NewPacket creates a new packet which will be sent to the Sentry server after its various options have been set.
NewQueuedEvent is used by SendQueue implementations to expose information about the events that they are sending to Sentry.
No description provided by the author
OSContext allows you to set the context describing the operating system that your application is running on.
Platform allows you to configure the platform reported to Sentry.
Release allows you to configure the application release version reported to Sentry with an event.
RuntimeContext allows you to set the information pertaining to the runtime that your program is executing on.
ServerName allows you to configure the hostname reported to Sentry with an event.
StackTrace allows you to add a StackTrace to the event you submit to Sentry, allowing you to quickly determine where in your code the event was generated.
Tags allow you to add additional tagging information to events which makes it possible to easily group and query similar events.
Timestamp allows you to provide a custom timestamp for an event that is sent to Sentry.
User allows you to include the details of a user that was interacting with your application when the error occurred.
UseSendQueue allows you to specify the send queue that will be used by a client.
UseTransport allows you to control which transport is used to send events for a specific client or packet.

# Constants

Debug is used to expose verbose information about events which occur during normal operation of the application.
ErrBadURL is returned when a DSN cannot be parsed due to formatting errors in its URL.
ErrMissingPrivateKey is returned when a DSN does not have a valid private key contained within its URL.
ErrMissingProjectID is returned when a DSN does not have a valid project ID contained within its URL.
ErrMissingPublicKey is returned when a DSN does not have a valid public key contained within its URL.
ErrMissingRootTLSCerts is used when this library cannot load the required RootCA certificates needed for its HTTPS transport.
Error represents exceptions which break the expected application flow.
ErrSendQueueFull is used when an attempt to enqueue a new event fails as a result of no buffer space being available.
ErrSendQueueShutdown is used when an attempt to enqueue a new event fails as a result of the queue having been shutdown already.
Fatal represents exceptions which result in the application exiting fatally.
Info is used to expose information about events which occur during normal operation of the application.
Warning represents events which are abnormal but do not prevent the application from operating correctly.

# Structs

DeviceContextInfo describes the device that your application is running on.
An ExceptionInfo describes the details of an exception that occurred within your application.
HTTPRequestInfo is a low-level interface which describes the details of an HTTP request made to a web server.
OSContextInfo describes the operating system that your application is running on.
UserInfo provides the fields that may be specified to describe a unique user of your application.

# Interfaces

A Breadcrumb keeps track of an action which took place in the application leading up to an event.
A BreadcrumbsList is responsible for keeping track of all the breadcrumbs that make up a sequence.
A Client is responsible for letting you interact with the Sentry API.
A Config allows you to control how events are sent to Sentry.
A FinalizableOption exposes a Finalize() method which is called by the Packet builder before its value is used.
An HTTPRequestOption describes an HTTP request's data.
The MergeableOption interface gives options the ability to merge themselves with other instances posessing the same class name.
An OmitableOption can opt to have itself left out of the packet by making an addition-time determination in its Omit() function.
An Option represents an object which can be written to the Sentry packet as a field with a given class name.
A Packet is a JSON serializable object that will be sent to the Sentry server to describe an event.
A QueuedEvent allows you to track the status of sending an event to Sentry.
QueuedEventInternal is an interface used by SendQueue implementations to "complete" a queued event once it has either been sent to Sentry, or sending failed with an error.
A SendQueue is used by the Sentry client to coordinate the transmission of events.
StackTraceOption wraps a stacktrace and gives you tools for selecting where it is sourced from or what is classified as an internal module.
Transport is the interface that any network transport must implement if it wishes to be used to send Sentry events.

# Type aliases

No description provided by the author
Severity represents a Sentry event severity (ranging from debug to fatal).