MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+124
@@ -0,0 +1,124 @@
|
||||
# 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
|
||||
|
||||
### Оборачивание логгера
|
||||
|
||||
```go
|
||||
wrappedLogger := sentry.WrapLogger(baseLogger, hub, []log.Level{log.LevelError, log.LevelFatal})
|
||||
```
|
||||
|
||||
### Обогащение событий
|
||||
|
||||
```go
|
||||
ctx = sentry.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
event.Extra["user_id"] = 12345
|
||||
})
|
||||
```
|
||||
|
||||
### Использование с контекстом
|
||||
|
||||
```go
|
||||
hub.CatchError(ctx, err, log.LevelError)
|
||||
```
|
||||
|
||||
Ошибка будет автоматически дополнена `requestId` и пользовательскими полями из `EnrichEvent`.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package sentry
|
||||
|
||||
// Config holds the configuration for Sentry integration.
|
||||
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
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
)
|
||||
|
||||
// contextEnrichmentKey is used as a context key for event enrichment functions.
|
||||
type contextEnrichmentKey struct{}
|
||||
|
||||
// contextKeyValue is the global context key for event enrichment.
|
||||
//
|
||||
//go:generate stringer -type=contextEnrichmentKey
|
||||
var (
|
||||
contextKeyValue = contextEnrichmentKey{}
|
||||
)
|
||||
|
||||
// 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 EventEnrichment func(event *sentry.Event)
|
||||
|
||||
// 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 EnrichEvent(ctx context.Context, enrichment EventEnrichment) context.Context {
|
||||
return context.WithValue(ctx, contextKeyValue, enrichment)
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
// 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"
|
||||
// })
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
// RequestIdKey is the key used to store the request ID in event extra data.
|
||||
RequestIdKey = "requestId"
|
||||
|
||||
// defaultTransportTimeout is the timeout for sending events to Sentry.
|
||||
defaultTransportTimeout = 3 * time.Second
|
||||
// defaultEventBufferSize is the buffer size for the Sentry transport.
|
||||
defaultEventBufferSize = 10
|
||||
)
|
||||
|
||||
// SdkHub is the concrete implementation of the Hub interface using the Sentry Go SDK.
|
||||
type SdkHub struct {
|
||||
hub *sentry.Hub
|
||||
}
|
||||
|
||||
// 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.
|
||||
func NewHubFromConfiguration(config Config) (Hub, error) {
|
||||
if !config.Enable {
|
||||
return NewNoopHub(), nil
|
||||
}
|
||||
|
||||
if config.Dsn == "" {
|
||||
return nil, errors.New("sentry is enabled. dsn must be specified. check sentry configuration")
|
||||
}
|
||||
|
||||
allTags := map[string]string{
|
||||
"version": config.ModuleVersion,
|
||||
}
|
||||
if config.InstanceId != "" {
|
||||
allTags["instanceId"] = config.InstanceId
|
||||
}
|
||||
|
||||
maps.Copy(allTags, config.Tags)
|
||||
|
||||
buffedTransport := sentry.NewHTTPTransport()
|
||||
buffedTransport.Timeout = defaultTransportTimeout
|
||||
buffedTransport.BufferSize = defaultEventBufferSize
|
||||
|
||||
client, err := sentry.NewClient(sentry.ClientOptions{
|
||||
Dsn: config.Dsn,
|
||||
Transport: buffedTransport,
|
||||
ServerName: config.ModuleName,
|
||||
Environment: config.Environment,
|
||||
Release: "undefined",
|
||||
Tags: allTags,
|
||||
Integrations: func(integrations []sentry.Integration) []sentry.Integration {
|
||||
filtered := make([]sentry.Integration, 0, len(integrations))
|
||||
ignoredIntegrations := map[string]bool{
|
||||
"Modules": true,
|
||||
"Environment": true,
|
||||
}
|
||||
for _, integration := range integrations {
|
||||
if ignoredIntegrations[integration.Name()] {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, integration)
|
||||
}
|
||||
return filtered
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create sdk client")
|
||||
}
|
||||
|
||||
hub := sentry.NewHub(client, sentry.NewScope())
|
||||
|
||||
return SdkHub{
|
||||
hub: hub,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 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 (s SdkHub) CatchError(ctx context.Context, err error, level log.Level) {
|
||||
eventLevel := sentry.LevelError
|
||||
levelFromMapping, ok := logLevelMapping[level]
|
||||
if ok {
|
||||
eventLevel = levelFromMapping
|
||||
}
|
||||
event := &sentry.Event{
|
||||
Level: eventLevel,
|
||||
Message: err.Error(),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
SetException(event, err)
|
||||
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId != "" {
|
||||
event.Tags = map[string]string{
|
||||
RequestIdKey: requestId,
|
||||
}
|
||||
}
|
||||
|
||||
s.CatchEvent(ctx, event)
|
||||
}
|
||||
|
||||
// CatchEvent captures a Sentry event directly.
|
||||
// The event is sent asynchronously to Sentry.
|
||||
func (s SdkHub) CatchEvent(ctx context.Context, event *sentry.Event) {
|
||||
s.hub.CaptureEvent(event)
|
||||
}
|
||||
|
||||
// Flush waits for all buffered events to be sent to Sentry.
|
||||
// It blocks until the transport timeout or until all events are sent.
|
||||
func (s SdkHub) Flush() {
|
||||
s.hub.Flush(defaultTransportTimeout)
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// Hub defines the interface for Sentry operations.
|
||||
// It provides methods for capturing errors and events, and flushing pending events.
|
||||
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()
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// logLevelMapping maps log levels to Sentry event levels.
|
||||
var (
|
||||
logLevelMapping = map[log.Level]sentry.Level{
|
||||
log.FatalLevel: sentry.LevelFatal,
|
||||
log.ErrorLevel: sentry.LevelError,
|
||||
log.WarnLevel: sentry.LevelWarning,
|
||||
log.InfoLevel: sentry.LevelInfo,
|
||||
log.DebugLevel: sentry.LevelDebug,
|
||||
}
|
||||
)
|
||||
|
||||
// Logger wraps a log.Logger and forwards log events to Sentry.
|
||||
// It provides structured logging with automatic error capture and context enrichment.
|
||||
type Logger struct {
|
||||
delegate log.Logger
|
||||
hub Hub
|
||||
supportedLevels map[log.Level]sentry.Level
|
||||
}
|
||||
|
||||
// WrapErrorLogger creates a Logger that captures only error-level events.
|
||||
// It delegates all logging to the underlying logger and sends errors to Sentry.
|
||||
func WrapErrorLogger(logger log.Logger, hub Hub) Logger {
|
||||
return WrapLogger(
|
||||
logger,
|
||||
hub,
|
||||
[]log.Level{log.ErrorLevel},
|
||||
)
|
||||
}
|
||||
|
||||
// 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 WrapLogger(logger log.Logger, hub Hub, supportedLevels []log.Level) Logger {
|
||||
levels := make(map[log.Level]sentry.Level)
|
||||
for _, level := range supportedLevels {
|
||||
levels[level] = logLevelMapping[level]
|
||||
}
|
||||
|
||||
return Logger{
|
||||
delegate: logger,
|
||||
hub: hub,
|
||||
supportedLevels: levels,
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (s Logger) Error(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Error(ctx, message, fields...)
|
||||
s.log(log.ErrorLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// Warn logs a warning message and forwards it to Sentry if WarnLevel is supported.
|
||||
func (s Logger) Warn(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Warn(ctx, message, fields...)
|
||||
s.log(log.WarnLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// Info logs an informational message and forwards it to Sentry if InfoLevel is supported.
|
||||
func (s Logger) Info(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Info(ctx, message, fields...)
|
||||
s.log(log.InfoLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message and forwards it to Sentry if DebugLevel is supported.
|
||||
func (s Logger) Debug(ctx context.Context, message any, fields ...log.Field) {
|
||||
s.delegate.Debug(ctx, message, fields...)
|
||||
s.log(log.DebugLevel, ctx, message, fields...)
|
||||
}
|
||||
|
||||
// log forwards a log event to Sentry if the level is supported and the hub is not a NoopHub.
|
||||
// It extracts error information from fields and enriches the event with context.
|
||||
func (s Logger) log(level log.Level, ctx context.Context, message any, fields ...log.Field) {
|
||||
sentryLevel, isSupported := s.supportedLevels[level]
|
||||
if !isSupported {
|
||||
return
|
||||
}
|
||||
|
||||
_, isNoopHub := s.hub.(NoopHub)
|
||||
if isNoopHub {
|
||||
return
|
||||
}
|
||||
|
||||
event := EventFromLog(sentryLevel, ctx, message, fields...)
|
||||
s.hub.CatchEvent(ctx, 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 EventFromLog(
|
||||
level sentry.Level,
|
||||
ctx context.Context,
|
||||
message any,
|
||||
fields ...log.Field,
|
||||
) *sentry.Event {
|
||||
errInLog, _ := message.(error)
|
||||
|
||||
tags := make(map[string]string, len(fields))
|
||||
for _, field := range log.ContextLogValues(ctx) {
|
||||
value := fieldToString(field)
|
||||
tags[field.Key] = value
|
||||
}
|
||||
for _, field := range fields {
|
||||
value := fieldToString(field)
|
||||
tags[field.Key] = value
|
||||
errField := errorFromField(field)
|
||||
if errInLog == nil {
|
||||
errInLog = errField
|
||||
}
|
||||
}
|
||||
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId != "" {
|
||||
tags["requestId"] = requestId
|
||||
}
|
||||
|
||||
event := &sentry.Event{
|
||||
Tags: tags,
|
||||
Level: level,
|
||||
Message: fmt.Sprintf("%v", message),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
if errInLog != nil {
|
||||
SetException(event, errInLog)
|
||||
}
|
||||
|
||||
enrichment, ok := ctx.Value(contextKeyValue).(EventEnrichment)
|
||||
if ok {
|
||||
enrichment(event)
|
||||
}
|
||||
|
||||
return event
|
||||
}
|
||||
|
||||
// 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.
|
||||
func SetException(e *sentry.Event, exception error) {
|
||||
err := exception
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < 10 && err != nil; i++ {
|
||||
e.Exception = append(e.Exception, sentry.Exception{
|
||||
Value: err.Error(),
|
||||
Type: reflect.TypeOf(err).String(),
|
||||
Stacktrace: sentry.ExtractStacktrace(err),
|
||||
})
|
||||
// nolint:errorlint
|
||||
switch previous := err.(type) {
|
||||
case interface{ Unwrap() error }:
|
||||
err = previous.Unwrap()
|
||||
case interface{ Cause() error }:
|
||||
err = previous.Cause()
|
||||
default:
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
|
||||
slices.Reverse(e.Exception)
|
||||
}
|
||||
|
||||
// nolint:forcetypeassert
|
||||
// fieldToString converts a log.Field to a Go string.
|
||||
// It handles various field types including strings, booleans, times, durations, and stringers.
|
||||
func fieldToString(field log.Field) string {
|
||||
switch {
|
||||
case field.String != "":
|
||||
return field.String
|
||||
case field.Type == zapcore.BoolType:
|
||||
return fmt.Sprintf("%v", field.Integer == 1)
|
||||
case field.Type == zapcore.ByteStringType:
|
||||
return string(field.Interface.([]byte))
|
||||
case field.Type == zapcore.StringerType:
|
||||
return field.Interface.(fmt.Stringer).String()
|
||||
case field.Type == zapcore.DurationType:
|
||||
return time.Duration(field.Integer).String()
|
||||
case field.Type == zapcore.TimeType:
|
||||
return time.Unix(0, field.Integer).In(field.Interface.(*time.Location)).Format("2006-01-02T15:04:05.000Z0700")
|
||||
case field.Interface != nil:
|
||||
return fmt.Sprintf("%v", field.Interface)
|
||||
default:
|
||||
return fmt.Sprintf("%v", field.Integer)
|
||||
}
|
||||
}
|
||||
|
||||
// errorFromField extracts an error from a log.Field if it is an error type.
|
||||
// Returns nil if the field is not an error.
|
||||
func errorFromField(field log.Field) error {
|
||||
if field.Type == zapcore.ErrorType {
|
||||
return field.Interface.(error) // nolint:forcetypeassert
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// 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.
|
||||
type NoopHub struct {
|
||||
}
|
||||
|
||||
// NewNoopHub creates a new NoopHub instance.
|
||||
func NewNoopHub() NoopHub {
|
||||
return NoopHub{}
|
||||
}
|
||||
|
||||
// CatchError discards the error without any action.
|
||||
func (n NoopHub) CatchError(ctx context.Context, err error, level log.Level) {
|
||||
}
|
||||
|
||||
// CatchEvent discards the event without any action.
|
||||
func (n NoopHub) CatchEvent(ctx context.Context, event *sentry.Event) {
|
||||
|
||||
}
|
||||
|
||||
// Flush performs no action.
|
||||
func (n NoopHub) Flush() {
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user