sentry

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2025 License: MIT Imports: 11 Imported by: 0

README

Go KM Sentry Integration

A reusable Go package that provides comprehensive Sentry integration for Go applications with built-in support for:

  • Gin HTTP Framework - Error handling and panic recovery middleware
  • gRPC Services - Unary server interceptors for error handling and panic recovery
  • Zerolog Integration - Automatic error logging to Sentry
  • Flexible Configuration - Environment-based or programmatic configuration

Features

  • 🚨 Automatic Error Capture - Captures errors and panics automatically
  • 🌐 HTTP & gRPC Support - Ready-to-use middleware for popular frameworks
  • 📝 Logging Integration - Seamless integration with zerolog
  • ⚙️ Configurable - Environment variables or programmatic configuration
  • 🔧 Production Ready - Includes proper error handling and recovery

Installation

go get github.com/jankojelickriptomat/km-sentry-go

Quick Start

Basic Setup
package main

import (
    "log"
    kmSentry "github.com/jankojelickriptomat/km-sentry-go"
)

func main() {
    // Initialize with default configuration (reads from environment variables)
    if err := kmSentry.Init(); err != nil {
        log.Fatal("Failed to initialize Sentry:", err)
    }
    defer kmSentry.Flush(2 * time.Second)

    // Your application code here
}
Custom Configuration
package main

import (
    "log"
    kmSentry "github.com/jankojelickriptomat/km-sentry-go"
)

func main() {
    config := kmSentry.Config{
        DSN:              "your-sentry-dsn",
        Environment:      "production",
        TracesSampleRate: 0.1,
        SampleRate:       0.1,
        Debug:            false,
        EnableLogging:    true,
    }

    if err := kmSentry.Init(config); err != nil {
        log.Fatal("Failed to initialize Sentry:", err)
    }
    defer kmSentry.Flush(2 * time.Second)
}

Environment Variables

The package supports the following environment variables:

Variable Description Default
SENTRY_DSN Sentry Data Source Name ""
SENTRY_ENVIRONMENT Environment name "development"
SENTRY_TRACES_SAMPLE_RATE Traces sample rate (0.0-1.0) "0.05"
SENTRY_SAMPLE_RATE Error sample rate (0.0-1.0) "0.05"
SENTRY_DEBUG Enable debug mode "development"
ENV Fallback for environment "development"

Usage Examples

Gin HTTP Server
package main

import (
    "github.com/gin-gonic/gin"
    kmSentry "github.com/jankojelickriptomat/km-sentry-go"
)

func main() {
    // Initialize Sentry
    kmSentry.Init()
    defer sentry.Flush(2 * time.Second)

    // Setup Gin with Sentry middleware
    r := gin.New()
    r.Use(sentry.GinRecoveryInterceptor()) // Panic recovery
    r.Use(sentry.GinErrorInterceptor())    // Error handling

    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "Hello World"})
    })

    r.GET("/error", func(c *gin.Context) {
        c.Error(errors.New("test error")) // Will be sent to Sentry
    })

    r.Run(":8080")
}
gRPC Server
package main

import (
    "google.golang.org/grpc"
    sentry "github.com/jankojelickriptomat/km-sentry-go"
)

func main() {
    // Initialize Sentry
    sentry.Init()
    defer sentry.Flush(2 * time.Second)

    // Setup gRPC server with Sentry interceptors
    s := grpc.NewServer(
        grpc.ChainUnaryInterceptor(
            sentry.GrpcErrorInterceptor,  // Error handling
            sentry.GrpcPanicInterceptor,  // Panic recovery
        ),
    )

    // Register your services here
    // pb.RegisterYourServiceServer(s, &yourService{})

    lis, _ := net.Listen("tcp", ":8090")
    s.Serve(lis)
}
Manual Error Capture
package main

import (
    "errors"
    kmSentry "github.com/jankojelickriptomat/km-sentry-go"
)

func main() {
    kmSentry.Init()
    defer kmSentry.Flush(2 * time.Second)

    // Capture exceptions manually
    err := errors.New("something went wrong")
    kmSentry.CaptureException(err)

    // Capture messages
    kmSentry.CaptureMessage("Custom message for debugging")

    // Handle panics
    defer kmSentry.HandleRecovery()

    // Your code that might panic
}

API Reference

Initialization Functions
  • Init(config Config) error - Initialize with custom configuration
  • Init() error - Initialize with default configuration
  • DefaultConfig() Config - Get default configuration
Error Handling Functions
  • CaptureException(err error) - Capture an error
  • CaptureMessage(message string) - Capture a message
  • HandleRecovery() - Handle panics (use with defer)
  • Flush(timeout time.Duration) bool - Flush pending events
Middleware Functions
  • GinErrorInterceptor() gin.HandlerFunc - Gin error middleware
  • GinRecoveryInterceptor() gin.HandlerFunc - Gin panic recovery middleware
  • GrpcErrorInterceptor - gRPC error interceptor
  • GrpcPanicInterceptor - gRPC panic recovery interceptor

Configuration

The Config struct supports the following fields:

type Config struct {
    DSN              string  // Sentry DSN
    Environment      string  // Environment (dev, staging, prod)
    TracesSampleRate float64 // Traces sample rate (0.0 to 1.0)
    SampleRate       float64 // Error sample rate (0.0 to 1.0)
    Debug            bool    // Enable debug mode
    EnableLogging    bool    // Enable zerolog integration
}

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Documentation

Overview

Package sentry provides a reusable Sentry integration for Go applications with support for Gin HTTP framework and gRPC services.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptureException

func CaptureException(err error)

func CaptureMessage

func CaptureMessage(message string)

func Flush

func Flush(timeout time.Duration) bool

func GinErrorInterceptor

func GinErrorInterceptor() gin.HandlerFunc

func GinRecoveryInterceptor

func GinRecoveryInterceptor() gin.HandlerFunc

GinRecoveryInterceptor returns a Gin middleware for panic recovery

func GinSentryMiddleware

func GinSentryMiddleware() gin.HandlerFunc

func GrpcErrorInterceptor

func GrpcErrorInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

func GrpcPanicInterceptor

func GrpcPanicInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

func HandleRecovery

func HandleRecovery()

func Init

func Init() error

Types

This section is empty.

Directories

Path Synopsis
examples
gin-example command
grpc-example command

Jump to

Keyboard shortcuts

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