raven

package module
v0.2.0-aurora Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2021 License: BSD-3-Clause Imports: 24 Imported by: 0

README

raven

Build Status Go Report Card GoDoc


The raven-go SDK is no longer maintained and was superseded by the sentry-go SDK. Learn more about the project on GitHub and check out the migration guide.


raven is the official Go SDK for the Sentry event/error logging system.

Installation

go get github.com/getsentry/raven-go

Note: Go 1.7 and newer are supported.

Documentation

Overview

Package raven implements a client for the Sentry error logging service.

Example
// ... i.e. raisedErr is incoming error
var raisedErr error
// sentry DSN generated by Sentry server
var sentryDSN string
// r is a request performed when error occurred
var r *http.Request
client, err := New(sentryDSN)
if err != nil {
	log.Fatal(err)
}
trace := NewStacktrace(0, 2, nil)
packet := NewPacket(raisedErr.Error(), NewException(raisedErr, trace), NewHttp(r))
eventID, ch := client.Capture(packet, nil)
if err = <-ch; err != nil {
	log.Fatal(err)
}
message := fmt.Sprintf("Captured error with id %s: %q", eventID, raisedErr)
log.Println(message)
Output:

Index

Examples

Constants

View Source
const (
	DEBUG   = Severity("debug")
	INFO    = Severity("info")
	WARNING = Severity("warning")
	ERROR   = Severity("error")
	FATAL   = Severity("fatal")
)

http://docs.python.org/2/howto/logging.html#logging-levels

Variables

View Source
var (
	ErrPacketDropped         = errors.New("raven: packet dropped")
	ErrUnableToUnmarshalJSON = errors.New("raven: unable to unmarshal JSON")
	ErrMissingUser           = errors.New("raven: dsn missing public key and/or password")
	ErrMissingProjectID      = errors.New("raven: dsn missing project id")
	ErrInvalidSampleRate     = errors.New("raven: sample rate should be between 0 and 1")
)

Internal SDK Error types

View Source
var DefaultClient = newClient(nil)

DefaultClient initialize a default *Client instance

View Source
var MaxQueueBuffer = 100

MaxQueueBuffer the maximum number of packets that will be buffered waiting to be delivered. Packets will be dropped if the buffer is full. Used by NewClient.

Functions

func Capture

func Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error)

Capture asynchronously delivers a packet to the Sentry server with the default *Client. It is a no-op when client is nil. A channel is provided if it is important to check for a send's success.

func CaptureError

func CaptureError(err error, tags map[string]string, interfaces ...Interface) string

CaptureError formats and delivers an error to the Sentry server using the default *Client. Adds a stacktrace to the packet, excluding the call to this method.

func CaptureErrorAndWait

func CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string

CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent

func CaptureMessage

func CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string

CaptureMessage formats and delivers a string message to the Sentry server with the default *Client

func CaptureMessageAndWait

func CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string

CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent.

func CapturePanic

func CapturePanic(f func(), tags map[string]string, interfaces ...Interface) (interface{}, string)

CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs. If an error is captured, both the error and the reported Sentry error ID are returned.

func CapturePanicAndWait

func CapturePanicAndWait(f func(), tags map[string]string, interfaces ...Interface) (interface{}, string)

CapturePanicAndWait is identical to CapturePanic, except it blocks and assures that the event was sent

func Cause

func Cause(err error) error

Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If the error does not implement Cause, the original error will be returned.

If the cause of the error is nil, then the original error will be returned.

If the error is nil, nil will be returned without further investigation.

Will return the deepest cause which is not nil.

func ClearContext

func ClearContext()

ClearContext clears Context interface on default client by removing tags, user and request information

func Close

func Close()

Close defaults client event queue

func IncludePaths

func IncludePaths() []string

IncludePaths returns configured includePaths of default client

func ProjectID

func ProjectID() string

ProjectID returns configured ProjectID of default client

func Recoverer

func Recoverer(handler http.Handler) http.Handler

Recoverer wraps the stdlib net/http Mux. Example:

 mux := http.NewServeMux
 ...
	http.Handle("/", raven.Recoverer(mux))

func RecoveryHandler

func RecoveryHandler(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request)

RecoveryHandler uses Recoverer to wrap the stdlib net/http Mux. Example:

http.HandleFunc("/", raven.RecoveryHandler(func(w http.ResponseWriter, r *http.Request) {
	...
}))

func Release

func Release() string

Release returns configured Release of default client

func SetDSN

func SetDSN(dsn string) error

SetDSN sets the DSN for the default *Client instance

func SetDebug

func SetDebug(debug bool)

SetDebug sets the "debug" config on the default *Client

func SetDefaultLoggerName

func SetDefaultLoggerName(name string)

SetDefaultLoggerName sets the "defaultLoggerName" on the default *Client

func SetEnvironment

func SetEnvironment(environment string)

SetEnvironment sets the "environment" tag on the default *Client

func SetHttpContext

func SetHttpContext(h *Http)

SetHttpContext updates Http of Context interface on default client

func SetIgnoreErrors

func SetIgnoreErrors(errs ...string) error

SetIgnoreErrors updates ignoreErrors config on default client

func SetIncludePaths

func SetIncludePaths(p []string)

SetIncludePaths updates includePaths config on default client

func SetMaxQueueBuffer

func SetMaxQueueBuffer(maxCount int)

func SetRelease

func SetRelease(release string)

SetRelease sets the "release" tag on the default *Client

func SetSampleRate

func SetSampleRate(rate float32) error

SetSampleRate sets the "sample rate" on the degault *Client

func SetSourceCodeLoader

func SetSourceCodeLoader(loader SourceCodeLoader)

SetSourceCodeLoader overrides currently used loader for the new one

func SetTagsContext

func SetTagsContext(t map[string]string)

SetTagsContext updates Tags of Context interface on default client

func SetUserContext

func SetUserContext(u *User)

SetUserContext updates User of Context interface on default client

func URL

func URL() string

URL returns configured url of default client

func Wait

func Wait()

Wait blocks and waits for all events to finish being sent to Sentry server

func WrapWithExtra

func WrapWithExtra(err error, extraInfo map[string]interface{}) error

WrapWithExtra adds extra data to an error before reporting to Sentry

Types

type Client

type Client struct {
	Tags map[string]string

	Transport Transport

	// DropHandler is called when a packet is dropped because the buffer is full.
	DropHandler func(*Packet)
	// contains filtered or unexported fields
}

Client encapsulates a connection to a Sentry server. It must be initialized by calling NewClient. Modification of fields concurrently with Send or after calling Report for the first time is not thread-safe.

func New

func New(dsn string) (*Client, error)

New constructs a new Sentry client instance

func NewClient deprecated

func NewClient(dsn string, tags map[string]string) (*Client, error)

NewClient constructs a Sentry client and spawns a background goroutine to handle packets sent by Client.Report.

Deprecated: use New and NewWithTags instead

func NewWithTags

func NewWithTags(dsn string, tags map[string]string) (*Client, error)

NewWithTags constructs a new Sentry client instance with default tags.

func (*Client) Capture

func (client *Client) Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error)

Capture asynchronously delivers a packet to the Sentry server. It is a no-op when client is nil. A channel is provided if it is important to check for a send's success.

func (*Client) CaptureError

func (client *Client) CaptureError(err error, tags map[string]string, interfaces ...Interface) string

CaptureError formats and delivers an error to the Sentry server. Adds a stacktrace to the packet, excluding the call to this method.

func (*Client) CaptureErrorAndWait

func (client *Client) CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string

CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent

func (*Client) CaptureMessage

func (client *Client) CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string

CaptureMessage formats and delivers a string message to the Sentry server.

func (*Client) CaptureMessageAndWait

func (client *Client) CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string

CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent.

func (*Client) CapturePanic

func (client *Client) CapturePanic(f func(), tags map[string]string, interfaces ...Interface) (err interface{}, errorID string)

CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs. If an error is captured, both the error and the reported Sentry error ID are returned.

func (*Client) CapturePanicAndWait

func (client *Client) CapturePanicAndWait(f func(), tags map[string]string, interfaces ...Interface) (err interface{}, errorID string)

CapturePanicAndWait is identical to CapturePanic, except it blocks and assures that the event was sent

func (*Client) ClearContext

func (client *Client) ClearContext()

ClearContext clears Context interface on given client by removing tags, user and request information

func (*Client) Close

func (client *Client) Close()

Close given clients event queue

func (*Client) IncludePaths

func (client *Client) IncludePaths() []string

IncludePaths returns configured includePaths of given client

func (*Client) ProjectID

func (client *Client) ProjectID() string

ProjectID returns configured ProjectID of given client

func (*Client) Release

func (client *Client) Release() string

Release returns configured Release of given client

func (*Client) SetDSN

func (client *Client) SetDSN(dsn string) error

SetDSN updates a client with a new DSN. It safe to call after and concurrently with calls to Report and Send.

func (*Client) SetDebug

func (client *Client) SetDebug(debug bool)

func (*Client) SetDefaultLoggerName

func (client *Client) SetDefaultLoggerName(name string)

SetDefaultLoggerName sets the default logger name.

func (*Client) SetEnvironment

func (client *Client) SetEnvironment(environment string)

SetEnvironment sets the "environment" tag.

func (*Client) SetHttpContext

func (client *Client) SetHttpContext(h *Http)

SetHttpContext updates Http of Context interface on given client

func (*Client) SetIgnoreErrors

func (client *Client) SetIgnoreErrors(errs []string) error

SetIgnoreErrors updates ignoreErrors config on given client

func (*Client) SetIncludePaths

func (client *Client) SetIncludePaths(p []string)

SetIncludePaths updates includePaths config on given client

func (*Client) SetRelease

func (client *Client) SetRelease(release string)

SetRelease sets the "release" tag.

func (*Client) SetSampleRate

func (client *Client) SetSampleRate(rate float32) error

SetSampleRate sets how much sampling we want on client side

func (*Client) SetTagsContext

func (client *Client) SetTagsContext(t map[string]string)

SetTagsContext updates Tags of Context interface on given client

func (*Client) SetUserContext

func (client *Client) SetUserContext(u *User)

SetUserContext updates User of Context interface on given client

func (*Client) URL

func (client *Client) URL() string

URL returns configured url of given client

func (*Client) Wait

func (client *Client) Wait()

Wait blocks and waits for all events to finish being sent to Sentry server

type Culpriter

type Culpriter interface {
	Culprit() string
}

Culpriter holds information about the exception culprit

type ErrWithExtra

type ErrWithExtra interface {
	Cause() error
	// contains filtered or unexported methods
}

ErrWithExtra links Error with attached user-provided extras that will be reported alongside the Error

type Exception

type Exception struct {
	// Required
	Value string `json:"value"`

	// Optional
	Type       string      `json:"type,omitempty"`
	Module     string      `json:"module,omitempty"`
	Stacktrace *Stacktrace `json:"stacktrace,omitempty"`
}

Exception defines Sentry's spec compliant interface holding Exception information - https://docs.sentry.io/development/sdk-dev/interfaces/exception/

func NewException

func NewException(err error, stacktrace *Stacktrace) *Exception

NewException constructs an Exception using provided Error and Stacktrace

func (*Exception) Class

func (e *Exception) Class() string

Class provides name of implemented Sentry's interface

func (*Exception) Culprit

func (e *Exception) Culprit() string

Culprit tries to read top-most error message from Exception's stacktrace

type Exceptions

type Exceptions struct {
	// Required
	Values []*Exception `json:"values"`
}

Exceptions defines Sentry's spec compliant interface holding Exceptions information - https://docs.sentry.io/development/sdk-dev/interfaces/exception/

func (Exceptions) Class

func (es Exceptions) Class() string

Class provides name of implemented Sentry's interface

type Extra

type Extra map[string]interface{}

Extra keeps track of any additional information that developer wants to attach to the final packet

type HTTPTransport

type HTTPTransport struct {
	*http.Client
}

HTTPTransport is the default transport, delivering packets to Sentry via the HTTP API.

func (*HTTPTransport) Send

func (t *HTTPTransport) Send(url, authHeader string, packet *Packet) error

Send uses HTTPTransport to send a Packet to configured Sentry's DSN endpoint

type Http

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

	// Optional
	Cookies string            `json:"cookies,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	Env     map[string]string `json:"env,omitempty"`

	// Must be either a string or map[string]string
	Data interface{} `json:"data,omitempty"`
}

Http defines Sentry's spec compliant interface holding Request information - https://docs.sentry.io/development/sdk-dev/interfaces/http/

func NewHttp

func NewHttp(req *http.Request) *Http

NewHttp creates new HTTP object that follows Sentry's HTTP interface spec and will be attached to the Packet

func (*Http) Class

func (h *Http) Class() string

Class provides name of implemented Sentry's interface

type Interface

type Interface interface {
	// The Sentry class name. Example: sentry.interfaces.Stacktrace
	Class() string
}

An Interface is a Sentry interface that will be serialized as JSON. It must implement json.Marshaler or use json struct tags.

type Message

type Message struct {
	// Required
	Message string `json:"message"`

	// Optional
	Params []interface{} `json:"params,omitempty"`
}

Message defines Sentry's spec compliant interface holding Message information - https://docs.sentry.io/development/sdk-dev/interfaces/message/

func (*Message) Class

func (m *Message) Class() string

Class provides name of implemented Sentry's interface

type Packet

type Packet struct {
	// Required
	Message string `json:"message"`

	// Required, set automatically by Client.Send/Report via Packet.Init if blank
	EventID   string    `json:"event_id"`
	Project   string    `json:"project"`
	Timestamp Timestamp `json:"timestamp"`
	Level     Severity  `json:"level"`
	Logger    string    `json:"logger"`

	// Optional
	Platform    string            `json:"platform,omitempty"`
	Culprit     string            `json:"culprit,omitempty"`
	ServerName  string            `json:"server_name,omitempty"`
	Release     string            `json:"release,omitempty"`
	Environment string            `json:"environment,omitempty"`
	Tags        Tags              `json:"tags,omitempty"`
	Modules     map[string]string `json:"modules,omitempty"`
	Fingerprint []string          `json:"fingerprint,omitempty"`
	Extra       Extra             `json:"extra,omitempty"`

	Interfaces []Interface `json:"-"`
}

Packet defines Sentry's spec compliant interface holding Event information (top-level object) - https://docs.sentry.io/development/sdk-dev/attributes/

func NewPacket

func NewPacket(message string, interfaces ...Interface) *Packet

NewPacket constructs a packet with the specified message and interfaces.

func NewPacketWithExtra

func NewPacketWithExtra(message string, extra Extra, interfaces ...Interface) *Packet

NewPacketWithExtra constructs a packet with the specified message, extra information, and interfaces.

func (*Packet) AddTags

func (packet *Packet) AddTags(tags map[string]string)

AddTags appends new tags to the existing ones

func (*Packet) Init

func (packet *Packet) Init(project string) error

Init initializes required fields in a packet. It is typically called by Client.Send/Report automatically.

func (*Packet) JSON

func (packet *Packet) JSON() ([]byte, error)

JSON encodes packet into JSON format that will be sent to the server

type Query

type Query struct {
	// Required
	Query string `json:"query"`

	// Optional
	Engine string `json:"engine,omitempty"`
}

Query defines Sentry's spec compliant interface holding Context information - https://docs.sentry.io/development/sdk-dev/interfaces/contexts/

func (*Query) Class

func (q *Query) Class() string

Class provides name of implemented Sentry's interface

type Severity

type Severity string

Severity used in the level attribute of a message

type SourceCodeLoader

type SourceCodeLoader interface {
	Load(filename string, line, context int) ([][]byte, int)
}

SourceCodeLoader allows to read source code files from the current fs

type Stacktrace

type Stacktrace struct {
	// Required
	Frames []*StacktraceFrame `json:"frames"`
}

Stacktrace defines Sentry's spec compliant interface holding Stacktrace information - https://docs.sentry.io/development/sdk-dev/interfaces/stacktrace/

func GetOrNewStacktrace

func GetOrNewStacktrace(err error, skip int, context int, appPackagePrefixes []string) *Stacktrace

GetOrNewStacktrace tries to get stacktrace from err as an interface of github.com/pkg/errors, or else NewStacktrace()

func NewStacktrace

func NewStacktrace(skip int, context int, appPackagePrefixes []string) *Stacktrace

NewStacktrace intializes and populates a new stacktrace, skipping skip frames.

context is the number of surrounding lines that should be included for context. Setting context to 3 would try to get seven lines. Setting context to -1 returns one line with no surrounding context, and 0 returns no context.

appPackagePrefixes is a list of prefixes used to check whether a package should be considered "in app".

func (*Stacktrace) Class

func (s *Stacktrace) Class() string

Class provides name of implemented Sentry's interface

func (*Stacktrace) Culprit

func (s *Stacktrace) Culprit() string

Culprit iterates through stacktrace frames and returns first in-app frame's information

type StacktraceFrame

type StacktraceFrame struct {
	// At least one required
	Filename string `json:"filename,omitempty"`
	Function string `json:"function,omitempty"`
	Module   string `json:"module,omitempty"`

	// Optional
	Lineno       int      `json:"lineno,omitempty"`
	Colno        int      `json:"colno,omitempty"`
	AbsolutePath string   `json:"abs_path,omitempty"`
	ContextLine  string   `json:"context_line,omitempty"`
	PreContext   []string `json:"pre_context,omitempty"`
	PostContext  []string `json:"post_context,omitempty"`
	InApp        bool     `json:"in_app"`
}

StacktraceFrame defines Sentry's spec compliant interface holding Frame information - https://docs.sentry.io/development/sdk-dev/interfaces/stacktrace/

func NewStacktraceFrame

func NewStacktraceFrame(pc uintptr, fName, file string, line, context int, appPackagePrefixes []string) *StacktraceFrame

NewStacktraceFrame builds a single frame using data returned from runtime.Caller.

context is the number of surrounding lines that should be included for context. Setting context to 3 would try to get seven lines. Setting context to -1 returns one line with no surrounding context, and 0 returns no context.

appPackagePrefixes is a list of prefixes used to check whether a package should be considered "in app".

type Tag

type Tag struct {
	Key   string
	Value string
}

Tag is a key:value pair of strings provided by user to better categorize events

func (*Tag) MarshalJSON

func (t *Tag) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a tag

func (*Tag) UnmarshalJSON

func (t *Tag) UnmarshalJSON(data []byte) error

UnmarshalJSON sets tag to parsed JSON data

type Tags

type Tags []Tag

Tags keep track of user configured tags

func (*Tags) UnmarshalJSON

func (t *Tags) UnmarshalJSON(data []byte) error

UnmarshalJSON sets tags to parsed JSON data

type Template

type Template struct {
	// Required
	Filename    string `json:"filename"`
	Lineno      int    `json:"lineno"`
	ContextLine string `json:"context_line"`

	// Optional
	PreContext   []string `json:"pre_context,omitempty"`
	PostContext  []string `json:"post_context,omitempty"`
	AbsolutePath string   `json:"abs_path,omitempty"`
}

Template defines Sentry's spec compliant interface holding Template information - https://docs.sentry.io/development/sdk-dev/interfaces/template/

func (*Template) Class

func (t *Template) Class() string

Class provides name of implemented Sentry's interface

type Timestamp

type Timestamp time.Time

Timestamp holds the creation time of a Packet

func (Timestamp) Format

func (timestamp Timestamp) Format(format string) string

Format return timestamp in configured timestampFormat

func (Timestamp) MarshalJSON

func (timestamp Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a timestamp

func (*Timestamp) UnmarshalJSON

func (timestamp *Timestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON sets timestamp to parsed JSON data

type Transport

type Transport interface {
	Send(url, authHeader string, packet *Packet) error
}

Transport used in Capture calls that handles communication with the Sentry servers

type User

type User struct {
	// All fields are optional
	ID       string `json:"id,omitempty"`
	Username string `json:"username,omitempty"`
	Email    string `json:"email,omitempty"`
	IP       string `json:"ip_address,omitempty"`
}

User defines Sentry's spec compliant interface holding User information - https://docs.sentry.io/development/sdk-dev/interfaces/user/

func (*User) Class

func (h *User) Class() string

Class provides name of implemented Sentry's interface

type Writer

type Writer struct {
	Client *Client
	Level  Severity
	Logger string // Logger name reported to Sentry
}

Writer holds all the information about the message that will be reported to Sentry

func (*Writer) Write

func (w *Writer) Write(p []byte) (int, error)

Write formats the byte slice p into a string, and sends a message to Sentry at the severity level indicated by the Writer w.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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