sentrylogrus

package module
v0.34.1 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 11 Imported by: 14

README


Official Sentry Logrus Hook for Sentry-go SDK

Go.dev Documentation: https://pkg.go.dev/github.com/getsentry/sentry-go/logrus
Example Usage: https://github.com/getsentry/sentry-go/tree/master/_examples/logrus

Installation

go get github.com/getsentry/sentry-go/logrus

Usage

import (
	"fmt"
	"os"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/getsentry/sentry-go"
	sentrylogrus "github.com/getsentry/sentry-go/logrus"
)

func main() {
	// Initialize Logrus
	logger := logrus.New()

	// Log DEBUG and higher level logs to STDERR
	logger.Level = logrus.DebugLevel
	logger.Out = os.Stderr

	// send logs on InfoLevel
	logHook, err := sentrylogrus.NewLogHook(
		[]logrus.Level{logrus.InfoLevel},
		sentry.ClientOptions{
			Dsn: "your-public-dsn",
			BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
				if hint.Context != nil {
					if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
						// You have access to the original Request
						fmt.Println(req)
					}
				}
				fmt.Println(event)
				return event
			},
			// need to have logs enabled
			EnableLogs:       true,
			Debug:            true,
			AttachStacktrace: true,
		})

	// send events on Error, Fatal, Panic levels
	eventHook, err := sentrylogrus.NewEventHook([]logrus.Level{
		logrus.ErrorLevel,
		logrus.FatalLevel,
		logrus.PanicLevel,
	}, sentry.ClientOptions{
		Dsn: "your-public-dsn",
		BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
			if hint.Context != nil {
				if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
					// You have access to the original Request
					fmt.Println(req)
				}
			}
			fmt.Println(event)
			return event
		},
		Debug:            true,
		AttachStacktrace: true,
	})
	if err != nil {
		panic(err)
	}
	defer eventHook.Flush(5 * time.Second)
	defer logHook.Flush(5 * time.Second)
	logger.AddHook(eventHook)
	logger.AddHook(logHook)

	// Flushes before calling os.Exit(1) when using logger.Fatal
	// (else all defers are not called, and Sentry does not have time to send the event)
	logrus.RegisterExitHandler(func() {
		eventHook.Flush(5 * time.Second)
		logHook.Flush(5 * time.Second)
	})

    // Log a InfoLevel entry STDERR which is sent as a log to Sentry
    logger.Infof("Application has started")

    // Log an error to STDERR which is also sent to Sentry
    logger.Errorf("oh no!")

    // Log a fatal error to STDERR, which sends an event to Sentry and terminates the application
    logger.Fatalf("can't continue...")
	
    // Example of logging with attributes
	logger.WithField("user", "test-user").Error("An error occurred")
}

Configuration

The sentrylogrus package accepts an array of logrus.Level and a struct of sentry.ClientOptions that allows you to configure how the hook will behave. The logrus.Level array defines which log levels should be sent to Sentry.

In addition, the Hook returned by sentrylogrus.New can be configured with the following options:

  • Fallback Functionality: Configure a fallback for handling errors during log transmission.
sentryHook.Fallback = func(entry *logrus.Entry, err error) {
    // Handle error
}
  • Setting default tags for all events sent to Sentry
sentryHook.AddTags(map[string]string{
    "key": "value",
})
  • Using hubProvider for Scoped Sentry Hubs

The hubProvider allows you to configure the Sentry hook to use a custom Sentry hub. This can be particularly useful when you want to scope logs to specific goroutines or operations, enabling more precise grouping and context in Sentry.

You can set a custom hubProvider function using the SetHubProvider method:

sentryHook.SetHubProvider(func() *sentry.Hub {
    // Create or return a specific Sentry hub
    return sentry.NewHub(sentry.GetCurrentHub().Client(), sentry.NewScope())
})

This ensures that logs from specific contexts or threads use the appropriate Sentry hub and scope.

Notes

  • Always call Flush or FlushWithContext to ensure all events are sent to Sentry before program termination

Documentation

Overview

Package sentrylogrus provides a simple Logrus hook for Sentry.

Index

Constants

View Source
const (
	// FieldRequest holds an *http.Request.
	FieldRequest = "request"
	// FieldUser holds a User or *User value.
	FieldUser = "user"
	// FieldTransaction holds a transaction ID as a string.
	FieldTransaction = "transaction"
	// FieldFingerprint holds a string slice ([]string), used to dictate the
	// grouping of this event.
	FieldFingerprint = "fingerprint"

	// These fields are simply omitted, as they are duplicated by the Sentry SDK.
	FieldGoVersion = "go_version"
	FieldMaxProcs  = "go_maxprocs"
)

These default log field keys are used to pass specific metadata in a way that Sentry understands. If they are found in the log fields, and the value is of the expected datatype, it will be converted from a generic field, into Sentry metadata.

These keys may be overridden by calling SetKey on the hook object.

Variables

This section is empty.

Functions

This section is empty.

Types

type FallbackFunc

type FallbackFunc func(*logrus.Entry) error

A FallbackFunc can be used to attempt to handle any errors in logging, before resorting to Logrus's standard error reporting.

type Hook

type Hook interface {
	// SetHubProvider sets a function to provide a hub for each log entry.
	SetHubProvider(provider func() *sentry.Hub)
	// AddTags adds tags to the hook's scope.
	AddTags(tags map[string]string)
	// SetFallback sets a fallback function for the eventHook.
	SetFallback(fb FallbackFunc)
	// SetKey sets an alternate field key for the eventHook.
	SetKey(oldKey, newKey string)
	// Levels returns the list of logging levels that will be sent to Sentry as events.
	Levels() []logrus.Level
	// Fire sends entry to Sentry as an event.
	Fire(entry *logrus.Entry) error
	// Flush waits until the underlying Sentry transport sends any buffered events.
	Flush(timeout time.Duration) bool
	// FlushWithContext waits for the underlying Sentry transport to send any buffered
	// events, blocking until the context's deadline is reached or the context is canceled.
	// It returns false if the context is canceled or its deadline expires before the events
	// are sent, meaning some events may not have been sent.
	FlushWithContext(ctx context.Context) bool
}

Hook is the logrus hook for Sentry.

It is not safe to configure the hook while logging is happening. Please perform all configuration before using it.

func New deprecated

func New(levels []logrus.Level, opts sentry.ClientOptions) (Hook, error)

Deprecated: New just makes an underlying call to NewEventHook.

func NewEventHook added in v0.34.0

func NewEventHook(levels []logrus.Level, opts sentry.ClientOptions) (Hook, error)

NewEventHook initializes a new Logrus hook which sends events to a new Sentry client configured according to opts.

func NewEventHookFromClient added in v0.34.0

func NewEventHookFromClient(levels []logrus.Level, client *sentry.Client) Hook

NewEventHookFromClient initializes a new Logrus hook which sends events to the provided sentry client.

func NewFromClient deprecated

func NewFromClient(levels []logrus.Level, client *sentry.Client) Hook

Deprecated: NewFromClient just makes an underlying call to NewEventHookFromClient.

func NewLogHook added in v0.34.0

func NewLogHook(levels []logrus.Level, opts sentry.ClientOptions) (Hook, error)

NewLogHook initializes a new Logrus hook which sends logs to a new Sentry client configured according to opts.

func NewLogHookFromClient added in v0.34.0

func NewLogHookFromClient(levels []logrus.Level, client *sentry.Client) Hook

NewLogHookFromClient initializes a new Logrus hook which sends logs to the provided sentry client.

Jump to

Keyboard shortcuts

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