sentry

package
v1.67.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 11 Imported by: 0

README

Package sentry

Пакет sentry предоставляет интеграцию с Sentry SDK для централизованного сбора и отправки ошибок и событий, с возможностью обогащения контекста через context.Context и функции обогащения событий.

Types

Config

Конфигурация для sentry

Fields:

Enable bool

Флаг включения Sentry.

Dsn string

DSN Sentry.

ModuleName string

Имя сервиса/модуля.

ModuleVersion string

Версия модуля.

Environment string

Окружение (например, prod, dev).

InstanceId string

Уникальный ID инстанса.

Tags map[string]string

Дополнительные произвольные теги.

Hub

Интерфейс Hub для отправки ошибок и событий.

Methods:

CatchError(ctx context.Context, err error, level log.Level)

Отправить ошибку с уровнем логирования.

CatchEvent(ctx context.Context, event *sentry.Event)

Отправить события напрямую.

Flush()

Подождать отправки всех событий.

EventEnrichment

Функция обогащения события — добавляет произвольные данные в sentry.Event.

Logger

  • Проксирует все методы логгера.

  • Автоматически отправляет события в Sentry, если уровень лога присутствует в supportedLevels.

  • Добавляет в событие:

    • уровень логирования,
    • requestId из контекста (если есть),
    • ошибку (если передана в лог),
    • данные обогащения из контекста.

Реализации Hub

SdkHub

Реальная обёртка над sentry.Hub. Отправляет события в Sentry SDK.

NoopHub

Заглушка, которая ничего не делает. Используется, если Sentry отключён.

Functions

func NewHubFromConfiguration(config Config) (Hub, error)

Создаёт Hub на основе конфигурации. Возвращает NoopHub, если Enable == false.

func EnrichEvent(ctx context.Context, enrichment EventEnrichment) context.Context

Добавляет функцию обогащения события в контекст. Используется для динамического расширения sentry.Event в Logger.

func WrapLogger(logger log.Logger, hub Hub, supportedLevels []log.Level) Logger

Оборачивает логгер, чтобы автоматически отправлять события в Sentry на указанных уровнях (supportedLevels).

func WrapErrorLogger(logger log.Logger, hub Hub) Logger

Упрощённый вариант WrapLogger, логирует только ошибки (log.LevelError).

Usage

Оборачивание логгера
wrappedLogger := sentry.WrapLogger(baseLogger, hub, []log.Level{log.LevelError, log.LevelFatal})
Обогащение событий
ctx = sentry.EnrichEvent(ctx, func(event *sentry.Event) {
	event.Extra["user_id"] = 12345
})
Использование с контекстом
hub.CatchError(ctx, err, log.LevelError)

Ошибка будет автоматически дополнена requestId и пользовательскими полями из EnrichEvent.

Documentation

Overview

Package sentry provides integration with Sentry for error tracking and event monitoring.

This package wraps the Sentry Go SDK to provide a simple interface for capturing errors and events from your application. It includes support for log integration, event enrichment, and graceful fallback when Sentry is disabled.

Basic Usage

Create a hub from configuration:

hub, err := sentry.NewHubFromConfiguration(sentry.Config{
	Enable:        true,
	Dsn:           "your-sentry-dsn",
	ModuleName:    "my-service",
	ModuleVersion: "v1.0.0",
	Environment:   "production",
})

Wrap a logger to automatically capture log events:

logger := sentry.WrapErrorLogger(log.Default(), hub)
logger.Error(ctx, "something went wrong", log.String("key", "value"))

Event Enrichment

You can enrich events with custom context using EnrichEvent:

ctx := sentry.EnrichEvent(ctx, func(event *sentry.Event) {
	event.Tags["custom-tag"] = "custom-value"
})

Index

Constants

View Source
const (
	// RequestIdKey is the key used to store the request ID in event extra data.
	RequestIdKey = "requestId"
)

Variables

This section is empty.

Functions

func EnrichEvent

func EnrichEvent(ctx context.Context, enrichment EventEnrichment) context.Context

EnrichEvent adds an event enrichment function to the context. The enrichment function will be called for all subsequent log events in this context. This allows adding custom metadata to events based on runtime context.

Example:

ctx := sentry.EnrichEvent(ctx, func(event *sentry.Event) {
	event.Tags["user-id"] = userID
	event.Tags["request-type"] = "api"
})

func EventFromLog

func EventFromLog(
	level sentry.Level,
	ctx context.Context,
	message any,
	fields ...log.Field,
) *sentry.Event

EventFromLog creates a Sentry event from a log entry. It extracts the error from the message or fields, enriches the event with context values, and applies any event enrichment functions from the context. The returned event includes the request ID if present in the context.

func SetException

func SetException(e *sentry.Event, exception error)

SetException extracts the error chain from an error and sets it on the Sentry event. Unlike the Sentry SDK's SetException, it only includes stack traces where they exist. The exception list is reversed to show the root cause first.

Types

type Config

type Config struct {
	// Enable determines whether Sentry is enabled.
	Enable bool
	// Dsn is the Sentry Data Source Name. Required when Enable is true.
	Dsn string
	// ModuleName identifies the service or module sending events.
	ModuleName string
	// ModuleVersion is the version of the module.
	ModuleVersion string
	// Environment specifies the environment (e.g., "production", "development").
	Environment string
	// InstanceId uniquely identifies the running instance.
	InstanceId string
	// Tags are key-value pairs attached to all events.
	Tags map[string]string
}

Config holds the configuration for Sentry integration.

type EventEnrichment

type EventEnrichment func(event *sentry.Event)

EventEnrichment is a function type that modifies a Sentry event. It can be used to add custom tags, context, or other metadata to events.

type Hub

type Hub interface {
	// CatchError captures an error with the specified log level.
	// The error is extracted from the context and sent to Sentry.
	CatchError(ctx context.Context, err error, level log.Level)
	// CatchEvent captures a Sentry event directly.
	CatchEvent(ctx context.Context, event *sentry.Event)
	// Flush waits for any buffered events to be sent to Sentry.
	Flush()
}

Hub defines the interface for Sentry operations. It provides methods for capturing errors and events, and flushing pending events.

func NewHubFromConfiguration

func NewHubFromConfiguration(config Config) (Hub, error)

NewHubFromConfiguration creates a new Hub from the provided configuration. If Enable is false, it returns a NoopHub that discards all events. Returns an error if Dsn is empty when Enable is true.

The created Hub is safe for concurrent use.

type Logger

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

Logger wraps a log.Logger and forwards log events to Sentry. It provides structured logging with automatic error capture and context enrichment.

func WrapErrorLogger

func WrapErrorLogger(logger log.Logger, hub Hub) Logger

WrapErrorLogger creates a Logger that captures only error-level events. It delegates all logging to the underlying logger and sends errors to Sentry.

func WrapLogger

func WrapLogger(logger log.Logger, hub Hub, supportedLevels []log.Level) Logger

WrapLogger creates a Logger that captures events at the specified log levels. Only the levels in supportedLevels will be forwarded to Sentry. The returned Logger is safe for concurrent use.

func (Logger) Debug

func (s Logger) Debug(ctx context.Context, message any, fields ...log.Field)

Debug logs a debug message and forwards it to Sentry if DebugLevel is supported.

func (Logger) Error

func (s Logger) Error(ctx context.Context, message any, fields ...log.Field)

Error logs an error message and forwards it to Sentry if ErrorLevel is supported. It delegates to the underlying logger and captures the error with full context.

func (Logger) Info

func (s Logger) Info(ctx context.Context, message any, fields ...log.Field)

Info logs an informational message and forwards it to Sentry if InfoLevel is supported.

func (Logger) Warn

func (s Logger) Warn(ctx context.Context, message any, fields ...log.Field)

Warn logs a warning message and forwards it to Sentry if WarnLevel is supported.

type NoopHub

type NoopHub struct {
}

NoopHub is a no-operation implementation of the Hub interface. It discards all events and errors without sending them to Sentry. Use this when Sentry is disabled to avoid nil pointer issues. The NoopHub is safe for concurrent use.

func NewNoopHub

func NewNoopHub() NoopHub

NewNoopHub creates a new NoopHub instance.

func (NoopHub) CatchError

func (n NoopHub) CatchError(ctx context.Context, err error, level log.Level)

CatchError discards the error without any action.

func (NoopHub) CatchEvent

func (n NoopHub) CatchEvent(ctx context.Context, event *sentry.Event)

CatchEvent discards the event without any action.

func (NoopHub) Flush

func (n NoopHub) Flush()

Flush performs no action.

type SdkHub

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

SdkHub is the concrete implementation of the Hub interface using the Sentry Go SDK.

func (SdkHub) CatchError

func (s SdkHub) CatchError(ctx context.Context, err error, level log.Level)

CatchError captures an error with the specified log level. It maps the log level to a Sentry level and extracts the error stack trace. If a request ID is present in the context, it is added to the event.

func (SdkHub) CatchEvent

func (s SdkHub) CatchEvent(ctx context.Context, event *sentry.Event)

CatchEvent captures a Sentry event directly. The event is sent asynchronously to Sentry.

func (SdkHub) Flush

func (s SdkHub) Flush()

Flush waits for all buffered events to be sent to Sentry. It blocks until the transport timeout or until all events are sent.

Jump to

Keyboard shortcuts

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