sentrylogrus

package module
v0.49.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 9 Imported by: 17

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 and above
	logHook, err := sentrylogrus.NewLogHook(
		[]logrus.Level{
			logrus.InfoLevel,
			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
			},
			// need to have logs enabled
			Debug:            true,
			AttachStacktrace: true,
		})

	if err != nil {
		panic(err)
	}
	defer logHook.Flush(5 * time.Second)
	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 log)
	logrus.RegisterExitHandler(func() {
		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 as a log
	logger.Errorf("oh no!")

	// Log a fatal error to STDERR, which sends a log 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 logs are sent to Sentry before program termination

Documentation

Overview

Package sentrylogrus provides a simple Logrus hook for Sentry.

Index

Constants

View Source
const (

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

	LogrusOrigin = "auto.log.logrus"
)

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