### Install Sentry Echo Handler Source: https://github.com/getsentry/sentry-go/blob/master/echo/README.md Install the sentry-go/echo package using go get. ```sh go get github.com/getsentry/sentry-go/echo ``` -------------------------------- ### Install sentry-go SDK Source: https://github.com/getsentry/sentry-go/blob/master/README.md Install the latest version of the sentry-go SDK using go get. ```console go get github.com/getsentry/sentry-go@latest ``` -------------------------------- ### Install Sentry Fiber Handler Source: https://github.com/getsentry/sentry-go/blob/master/fiber/README.md Use `go get` to install the Sentry Fiber handler package. ```sh go get github.com/getsentry/sentry-go/fiber ``` -------------------------------- ### Install Sentry Zerolog Writer Source: https://github.com/getsentry/sentry-go/blob/master/zerolog/README.md Use 'go get' to install the Sentry Zerolog writer package. ```sh go get github.com/getsentry/sentry-go/zerolog ``` -------------------------------- ### Initialize Sentry and Setup HTTP Handler Source: https://github.com/getsentry/sentry-go/blob/master/http/README.md Initialize Sentry and then create and attach the Sentry HTTP handler to your routes. This example shows how to use both `Handle` for standard handlers and `HandleFunc` for function-based handlers, including one that panics. ```go import ( "fmt" "net/http" "github.com/getsentry/sentry-go" sentryhttp "github.com/getsentry/sentry-go/http" ) // To initialize Sentry's handler, you need to initialize Sentry itself beforehand if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Create an instance of sentryhttp sentryHandler := sentryhttp.New(sentryhttp.Options{}) // Once it's done, you can setup routes and attach the handler as one of your middleware http.Handle("/", sentryHandler.Handle(&handler{})) http.HandleFunc("/foo", sentryHandler.HandleFunc(func(rw http.ResponseWriter, r *http.Request) { panic("y tho") })) fmt.Println("Listening and serving HTTP on :3000") // And run it if err := http.ListenAndServe(":3000", nil); err != nil { panic(err) } ``` -------------------------------- ### Initialize Sentry and Echo App with Handler Source: https://github.com/getsentry/sentry-go/blob/master/echo/README.md Initialize Sentry, create an Echo app, and attach the sentryecho middleware. This example shows basic setup for logging and recovery. ```go import ( "fmt" "net/http" "github.com/getsentry/sentry-go" sentryecho "github.com/getsentry/sentry-go/echo" "github.com/labstack/echo/v5" "github.com/labstack/echo/v5/middleware" ) // To initialize Sentry's handler, you need to initialize Sentry itself beforehand if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Then create your app app := echo.New() app.Use(middleware.Logger()) app.Use(middleware.Recover()) // Once it's done, you can attach the handler as one of your middleware app.Use(sentryecho.New(sentryecho.Options{})) // Set up routes app.GET("/", func(ctx *echo.Context) error { return ctx.String(http.StatusOK, "Hello, World!") }) // And run it app.Logger.Fatal(app.Start(":3000")) ``` -------------------------------- ### Install Sentry Negroni Handler Source: https://github.com/getsentry/sentry-go/blob/master/negroni/README.md Install the Sentry Negroni handler using go get. ```sh go get github.com/getsentry/sentry-go/negroni ``` -------------------------------- ### Install Sentry fasthttp Handler Source: https://github.com/getsentry/sentry-go/blob/master/fasthttp/README.md Install the fasthttp handler for the sentry-go SDK using go get. ```sh go get github.com/getsentry/sentry-go/fasthttp ``` -------------------------------- ### Install Sentry Go HTTP Handler Source: https://github.com/getsentry/sentry-go/blob/master/http/README.md Use `go get` to install the Sentry Go HTTP handler package. ```sh go get github.com/getsentry/sentry-go/http ``` -------------------------------- ### Install Sentry Fiber v3 Handler Source: https://github.com/getsentry/sentry-go/blob/master/fiberv3/README.md Install the Sentry Fiber v3 handler using go get. This command fetches the necessary package for your project. ```sh go get github.com/getsentry/sentry-go/fiberv3 ``` -------------------------------- ### Install Sentry gRPC Interceptor Source: https://github.com/getsentry/sentry-go/blob/master/grpc/README.MD Install the Sentry gRPC interceptor package using go get. ```sh go get github.com/getsentry/sentry-go/grpc ``` -------------------------------- ### Initialize and Use Sentry fasthttp Handler Source: https://github.com/getsentry/sentry-go/blob/master/fasthttp/README.md Initialize Sentry and attach the fasthttp handler as middleware. This example demonstrates basic setup and error capturing. ```go import ( "fmt" "net/http" "github.com/getsentry/sentry-go" sentryfasthttp "github.com/getsentry/sentry-go/fasthttp" ) // To initialize Sentry's handler, you need to initialize Sentry itself beforehand if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Create an instance of sentryfasthttp sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{}) // Once it's done, you can attach the handler as one of your middlewares fastHTTPHandler := sentryHandler.Handle(func(ctx *fasthttp.RequestCtx) { panic("y tho") }) fmt.Println("Listening and serving HTTP on :3000") // And run it if err := fasthttp.ListenAndServe(":3000", fastHTTPHandler); err != nil { panic(err) } ``` -------------------------------- ### Install Sentry Iris Handler Source: https://github.com/getsentry/sentry-go/blob/master/iris/README.md Install the Sentry Iris handler package using go get. ```sh go get github.com/getsentry/sentry-go/iris ``` -------------------------------- ### Install Sentry Gin Handler Source: https://github.com/getsentry/sentry-go/blob/master/gin/README.md Install the Sentry Gin handler using go get. This command fetches the necessary package for integrating Sentry with your Gin application. ```sh go get github.com/getsentry/sentry-go/gin ``` -------------------------------- ### Backwards Compatibility Example Source: https://github.com/getsentry/sentry-go/blob/master/slog/README.MD Example showing the old and new way of configuring log levels. ```go // Old way (still works) handler := sentryslog.Option{ Level: slog.LevelWarn, // Will be converted to EventLevel: [Warn, Error, Fatal] }.NewSentryHandler(ctx) // New way (preferred) handler := sentryslog.Option{ EventLevel: []slog.Level{slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal}, LogLevel: []slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal}, }.NewSentryHandler(ctx) ``` -------------------------------- ### Usage Source: https://github.com/getsentry/sentry-go/blob/master/zap/README.md Example of initializing Sentry and using the zap Core to send logs. ```go package main import ( "context" "time" "github.com/getsentry/sentry-go" sentryzap "github.com/getsentry/sentry-go/zap" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) func main() { // Initialize Sentry with logs enabled err := sentry.Init(sentry.ClientOptions{ Dsn: "your-sentry-dsn", }) if err != nil { panic(err) } defer sentry.Flush(2 * time.Second) // Create the Sentry core ctx := context.Background() sentryCore := sentryzap.NewSentryCore(ctx, sentryzap.Option{ Level: []zapcore.Level{ zapcore.InfoLevel, zapcore.WarnLevel, zapcore.ErrorLevel, }, AddCaller: true, }) // Create a zap logger with the Sentry core logger := zap.New(sentryCore) // Log messages will be sent to Sentry logger.Info("Application started", zap.String("version", "1.0.0"), zap.String("environment", "production"), ) logger.Warn("High memory usage", zap.Float64("usage_percent", 85.5), ) logger.Error("Database connection failed", zap.Error(errors.New("connection timeout")), zap.String("host", "db.example.com"), ) } ``` -------------------------------- ### Usage Source: https://github.com/getsentry/sentry-go/blob/master/slog/README.MD Example of how to initialize and use the Sentry slog handler. ```go package main import ( "context" "log/slog" "github.com/getsentry/sentry-go" sentryslog "github.com/getsentry/sentry-go/slog" ) func main() { // Initialize Sentry err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", Debug: true, }) if err != nil { panic(err) } defer sentry.Flush(5 * time.Second) ctx := context.Background() handler := sentryslog.Option{ EventLevel: []slog.Level{slog.LevelError, sentryslog.LevelFatal}, // Only Error and Fatal as events LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Only Warn and Info as logs }.NewSentryHandler(ctx) logger := slog.New(handler) // Example logging logger.Info("This will be sent to sentry as a Log entry") logger.Error("An error occurred", "user", "test-user") // this will be sent as an Event // These will be ignored logger.Debug("This will be ignored") } ``` -------------------------------- ### Installation Source: https://github.com/getsentry/sentry-go/blob/master/zap/README.md Install the zap integration package for Go. ```bash go get github.com/getsentry/sentry-go/zap ``` -------------------------------- ### Usage Example Source: https://github.com/getsentry/sentry-go/blob/master/logrus/README.md Example demonstrating how to initialize Logrus, add Sentry hooks for different log levels, and log messages. ```go 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 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") } ``` -------------------------------- ### Configuring Sentry HTTP Handler Options Source: https://github.com/getsentry/sentry-go/blob/master/http/README.md Initialize the Sentry HTTP handler with custom options, such as `Repanic` and `WaitForDelivery`. This example also shows how to use the `HandleFunc` with a middleware for enhancing events before a panic occurs. ```go sentryHandler := sentryhttp.New(sentryhttp.Options{ Repanic: true, }) http.Handle("/", sentryHandler.Handle(&handler{})) http.HandleFunc("/foo", sentryHandler.HandleFunc( enhanceSentryEvent(func(rw http.ResponseWriter, r *http.Request) { panic("y tho") }), )) fmt.Println("Listening and serving HTTP on :3000") if err := http.ListenAndServe(":3000", nil); err != nil { panic(err) } ``` -------------------------------- ### Installation Source: https://github.com/getsentry/sentry-go/blob/master/logrus/README.md Install the Sentry Logrus hook using go get. ```sh go get github.com/getsentry/sentry-go/logrus ``` -------------------------------- ### Example Customization Source: https://github.com/getsentry/sentry-go/blob/master/slog/README.MD Example of customizing the Sentry slog handler with specific options. ```go handler := slogSentry.Option{ EventLevel: slog.LevelWarn, Converter: func(addSource bool, replaceAttr func([]string, slog.Attr) slog.Attr, attrs []slog.Attr, groups []string, record *slog.Record, hub *sentry.Hub) *sentry.Event { // Custom conversion logic return &sentry.Event{ Message: record.Message, } }, AddSource: true, }.NewSentryHandler() ``` -------------------------------- ### Installation Source: https://github.com/getsentry/sentry-go/blob/master/slog/README.MD Install the slog integration for sentry-go. ```sh go get github.com/getsentry/sentry-go/slog ``` -------------------------------- ### Use the Context() helper for dynamic trace propagation Source: https://github.com/getsentry/sentry-go/blob/master/zap/README.md Example of using the Context() helper with logger.With() for dynamic trace propagation. ```go // Create logger with base context sentryCore := sentryzap.NewSentryCore(context.Background(), sentryzap.Option{}) logger := zap.New(sentryCore) // Start a transaction span := sentry.StartTransaction(ctx, "operation.name") defer span.Finish() // Create a logger scoped to this transaction scopedLogger := logger.With(sentryzap.Context(span.Context())) // These logs will be associated with the transaction scopedLogger.Info("Processing started") scopedLogger.Info("Processing completed") ``` -------------------------------- ### Using with Multiple Cores (Tee) Source: https://github.com/getsentry/sentry-go/blob/master/zap/README.md Example of combining the Sentry core with a console core using zapcore.NewTee. ```go package main import ( "context" "os" "time" "github.com/getsentry/sentry-go" sentryzap "github.com/getsentry/sentry-go/zap" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) func main() { // Initialize Sentry sentry.Init(sentry.ClientOptions{ Dsn: "your-sentry-dsn", }) defer sentry.Flush(2 * time.Second) // Create encoder config encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder // Console core - logs everything to stdout consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig) consoleCore := zapcore.NewCore( consoleEncoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel, ) // Sentry core - only sends Warn and above to Sentry ctx := context.Background() sentryCore := sentryzap.NewSentryCore(ctx, sentryzap.Option{ Level: []zapcore.Level{ zapcore.WarnLevel, zapcore.ErrorLevel, }, }) // Combine cores combinedCore := zapcore.NewTee(consoleCore, sentryCore) // Create logger with caller info logger := zap.New(combinedCore, zap.AddCaller()) // Debug goes to console only logger.Debug("Debug message - console only") // Warn goes to both console and Sentry logger.Warn("Warning message - console and Sentry") } ``` -------------------------------- ### Pass context when creating the core Source: https://github.com/getsentry/sentry-go/blob/master/zap/README.md Example of passing context when creating the Sentry core to associate logs with a Sentry span. ```go ctx := context.Background() // Start a transaction span := sentry.StartSpan(ctx, "operation.name") defer span.Finish() // Create logger with the span's context ctx = span.Context() sentryCore := sentryzap.NewSentryCore(ctx, sentryzap.Option{}) logger := zap.New(sentryCore) // This log will be associated with the transaction logger.Info("Processing started") ``` -------------------------------- ### Initialize Sentry and Zerolog with Sentry Writer Source: https://github.com/getsentry/sentry-go/blob/master/zerolog/README.md Initialize Sentry, configure the Sentry Zerolog writer with desired options, and then initialize Zerolog with this writer. Ensure Sentry is flushed before program termination. ```go package main import ( time "github.com/rs/zerolog" "github.com/getsentry/sentry-go" sentryzerolog "github.com/getsentry/sentry-go/zerolog" ) func main() { // Initialize Sentry err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }) if err != nil { panic(err) } defer sentry.Flush(2 * time.Second) // Configure Sentry Zerolog Writer writer, err := sentryzerolog.New(sentryzerolog.Config{ ClientOptions: sentry.ClientOptions{ Dsn: "your-public-dsn", Debug: true, }, Options: sentryzerolog.Options{ Levels: []zerolog.Level{zerolog.ErrorLevel, zerolog.FatalLevel}, FlushTimeout: 3 * time.Second, WithBreadcrumbs: true, }, }) if err != nil { panic(err) } defer writer.Close() // Initialize Zerolog logger := zerolog.New(writer).With().Timestamp().Logger() // Example Logs logger.Info().Msg("This is an info message") // Breadcrumb logger.Error().Msg("This is an error message") // Captured as an event logger.Fatal().Msg("This is a fatal message") // Captured as an event and flushes } ``` -------------------------------- ### Prepare Release with Craft Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Use the `craft` tool to prepare a new release. This command typically handles packaging and versioning. ```console $ craft prepare X.X.X ``` -------------------------------- ### Import Necessary Packages Source: https://github.com/getsentry/sentry-go/blob/master/fiber/README.md Import the required packages for Fiber, Sentry, and the Sentry Fiber handler. ```go import ( "fmt" "github.com/gofiber/fiber/v2" "github.com/getsentry/sentry-go" sentryfiber "github.com/getsentry/sentry-go/fiber" "github.com/gofiber/fiber/v2/utils" ) ``` -------------------------------- ### Initialize Sentry and Fiber Handler Source: https://github.com/getsentry/sentry-go/blob/master/fiber/README.md Initialize the Sentry SDK with your DSN and create an instance of the Sentry Fiber handler. Attach the handler as middleware to your Fiber application. ```go if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Create an instance of sentryfiber sentryHandler := sentryfiber.New(sentryfiber.Options{}) // Once it's done, you can attach the handler as one of your middlewares app := fiber.New() app.Use(sentryHandler) // And run it app.Listen(":3000") ``` -------------------------------- ### Initialize Sentry and Attach Gin Handler Source: https://github.com/getsentry/sentry-go/blob/master/gin/README.md Initialize Sentry and attach the sentry-gin handler as middleware. Ensure Sentry is initialized before creating your Gin app and attaching the handler. ```go import ( "fmt" "net/http" "github.com/getsentry/sentry-go" sentrygin "github.com/getsentry/sentry-go/gin" "github.com/gin-gonic/gin" ) // To initialize Sentry's handler, you need to initialize Sentry itself beforehand if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Then create your app app := gin.Default() // Once it's done, you can attach the handler as one of your middleware app.Use(sentrygin.New(sentrygin.Options{})) // Set up routes app.GET("/", func(ctx *gin.Context) { ctx.String(http.StatusOK, "Hello world!") }) // And run it app.Run(":3000") ``` -------------------------------- ### Initialize Sentry and Attach Negroni Handler Source: https://github.com/getsentry/sentry-go/blob/master/negroni/README.md Initialize Sentry and attach the sentrynegroni handler as middleware to a Negroni application. Ensure Sentry is initialized before creating the app. ```go import ( "fmt" "net/http" "github.com/getsentry/sentry-go" sentrynegroni "github.com/getsentry/sentry-go/negroni" "github.com/urfave/negroni" ) // To initialize Sentry's handler, you need to initialize Sentry itself beforehand if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Then create your app app := negroni.Classic() // Once it's done, you can attach the handler as one of your middleware app.Use(sentrynegroni.New(sentrynegroni.Options{})) // Set up routes mux := http.NewServeMux() mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello world!") }) app.UseHandler(mux) // And run it http.ListenAndServe(":3000", app) ``` -------------------------------- ### Run All Tests Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Execute all automated tests for the project. This is a standard command for Go projects. ```console $ go test ``` -------------------------------- ### Publish Release with Craft Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Use the `craft` tool to publish a new release. This command typically handles uploading artifacts and tagging. ```console $ craft publish X.X.X ``` -------------------------------- ### Initialize Sentry and Attach Iris Handler Source: https://github.com/getsentry/sentry-go/blob/master/iris/README.md Initialize the Sentry SDK and then attach the sentryiris handler as middleware to your Iris application. ```go import ( "fmt" "github.com/getsentry/sentry-go" sentryiris "github.com/getsentry/sentry-go/iris" "github.com/kataras/iris/v12" ) // To initialize Sentry's handler, you need to initialize Sentry itself beforehand if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Then create your app app := iris.Default() // Once it's done, you can attach the handler as one of your middleware app.Use(sentryiris.New(sentryiris.Options{})) // Set up routes app.Get("/", func(ctx iris.Context) { ctx.Writef("Hello world!") }) // And run it app.Run(iris.Addr(":3000")) ``` -------------------------------- ### Lint Code with golangci-lint Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Run the `golangci-lint` tool to check code quality and style. Ensure your code adheres to project standards. ```console $ golangci-lint run ``` -------------------------------- ### Configure Sentry Negroni Handler Options Source: https://github.com/getsentry/sentry-go/blob/master/negroni/README.md Configure the sentrynegroni handler using Options for Repanic, WaitForDelivery, and Timeout. ```go // Whether Sentry should repanic after recovery, in most cases it should be set to true, // as negroni.Classic includes its own Recovery middleware that handles http responses. Repanic bool // Whether you want to block the request before moving forward with the response. // Because Negroni's default `Recovery` handler doesn't restart the application, // it's safe to either skip this option or set it to `false`. WaitForDelivery bool // Timeout for the event delivery requests. Timeout time.Duration ``` -------------------------------- ### Sentry Gin Handler Options Source: https://github.com/getsentry/sentry-go/blob/master/gin/README.md Configure the sentry-gin handler using the Options struct. Available options include Repanic, WaitForDelivery, and Timeout. ```go // Whether Sentry should repanic after recovery, in most cases it should be set to true, // as gin.Default includes its own Recovery middleware that handles http responses. Repanic bool // Whether you want to block the request before moving forward with the response. // Because Gin's default `Recovery` handler doesn't restart the application, // it's safe to either skip this option or set it to `false`. WaitForDelivery bool // Timeout for the event delivery requests. Timeout time.Duration ``` -------------------------------- ### Import Sentry Fiber v3 Handler Source: https://github.com/getsentry/sentry-go/blob/master/fiberv3/README.md Import the required packages for Sentry and the Fiber v3 handler into your Go application. Ensure all necessary modules are included. ```go import ( "fmt" fiber "github.com/gofiber/fiber/v3" "github.com/getsentry/sentry-go" sentryfiber "github.com/getsentry/sentry-go/fiberv3" ) ``` -------------------------------- ### Use Negroni's PanicHandlerFunc with Sentry Source: https://github.com/getsentry/sentry-go/blob/master/negroni/README.md Utilize Negroni's PanicHandlerFunc option with sentrynegroni.PanicHandlerFunc for a concise way to report panics to Sentry. ```go app := negroni.New() recovery := negroni.NewRecovery() recovery.PanicHandlerFunc = sentrynegroni.PanicHandlerFunc app.Use(recovery) mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("y tho") }) app.UseHandler(mux) http.ListenAndServe(":3000", app) ``` -------------------------------- ### Accessing Sentry Hub in Echo Context Source: https://github.com/getsentry/sentry-go/blob/master/echo/README.md Demonstrates how to retrieve the Sentry Hub from the Echo context and use it to set tags or capture messages within middleware and routes. ```go app := echo.New() app.Use(middleware.Logger()) app.Use(middleware.Recover()) app.Use(sentryecho.New(sentryecho.Options{ Repanic: true, })) app.Use(func(next echo.HandlerFunc) echo.HandlerFunc { return func(ctx *echo.Context) error { if hub := sentryecho.GetHubFromContext(ctx); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } return next(ctx) } }) app.GET("/", func(ctx *echo.Context) error { if hub := sentryecho.GetHubFromContext(ctx); hub != nil { hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } return ctx.String(http.StatusOK, "Hello, World!") }) app.GET("/foo", func(ctx *echo.Context) error { // sentryecho handler will catch it just fine. Also, because we attached "someRandomTag" // in the middleware before, it will be sent through as well panic("y tho") }) app.Logger.Fatal(app.Start(":3000")) ``` -------------------------------- ### Run Tests in Watch Mode Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Continuously run tests as files change using the `reflex` tool. Useful for TDD or rapid development cycles. ```console $ reflex -g '*.go' -d "none" -- sh -c 'printf "\n"; go test' ``` -------------------------------- ### Accessing Sentry Hub from Request Context Source: https://github.com/getsentry/sentry-go/blob/master/http/README.md Demonstrates how to retrieve the Sentry Hub from the request context within a handler to set tags and capture messages. Ensure the Sentry HTTP handler is used before this. ```go type handler struct{} func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { if hub := sentry.GetHubFromContext(r.Context()); hub != nil { hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } rw.WriteHeader(http.StatusOK) } ``` -------------------------------- ### Sentry Fiber Handler Options Source: https://github.com/getsentry/sentry-go/blob/master/fiber/README.md Configure the Sentry Fiber handler's behavior using the `Options` struct, including repanic behavior, waiting for delivery, and request timeouts. ```go // Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to false, // as fasthttp doesn't include it's own Recovery handler. Repanic bool // WaitForDelivery configures whether you want to block the request before moving forward with the response. // Because fasthttp doesn't include it's own `Recovery` handler, it will restart the application, // and event won't be delivered otherwise. WaitForDelivery bool // Timeout for the event delivery requests. Timeout time.Duration ``` -------------------------------- ### Configure sentryiris Options Source: https://github.com/getsentry/sentry-go/blob/master/iris/README.md Configure the sentryiris handler using the Options struct to control repanic behavior, delivery blocking, and timeouts. ```go // Whether Sentry should repanic after recovery, in most cases it should be set to true, // as iris.Default includes its own Recovery middleware that handles http responses. Repanic bool // Whether you want to block the request before moving forward with the response. // Because Iris's default `Recovery` handler doesn't restart the application, // it's safe to either skip this option or set it to `false`. WaitForDelivery bool // Timeout for the event delivery requests. Timeout time.Duration ``` -------------------------------- ### Run Tests with Data Race Detection Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Execute tests while enabling Go's built-in data race detector. Helps identify concurrency issues. ```console $ go test -race ``` -------------------------------- ### Sentry Echo Handler Options Source: https://github.com/getsentry/sentry-go/blob/master/echo/README.md Configuration options for the sentryecho handler, including repanic behavior, waiting for delivery, and request timeout. ```go // Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true, // as echo includes its own Recover middleware that handles http responses. Repanic bool // WaitForDelivery configures whether you want to block the request before moving forward with the response. // Because Echo's `Recover` handler doesn't restart the application, // it's safe to either skip this option or set it to `false`. WaitForDelivery bool // Timeout for the event delivery requests. Timeout time.Duration ``` -------------------------------- ### Generate Test Coverage Report Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Run tests with data race detection, generate a coverage profile, and open it as an HTML report. Useful for assessing test completeness. ```console $ go test -race -coverprofile=coverage.txt -covermode=atomic && go tool cover -html coverage.txt ``` -------------------------------- ### Sentry gRPC Server Options Source: https://github.com/getsentry/sentry-go/blob/master/grpc/README.MD Defines configuration options for the Sentry gRPC server interceptor, including panic recovery behavior, delivery waiting, and timeout settings. ```go type ServerOptions struct { // Repanic determines whether the application should re-panic after recovery. Repanic bool // WaitForDelivery determines if the interceptor should block until events are sent to Sentry. WaitForDelivery bool // Timeout sets the maximum duration for Sentry event delivery. Timeout time.Duration } ``` -------------------------------- ### Configure Sentry Fiber Handler Options Source: https://github.com/getsentry/sentry-go/blob/master/fiberv3/README.md Explore the configuration options for the Sentry Fiber v3 handler, including Repanic, WaitForDelivery, and Timeout. These settings control handler behavior. ```go // Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to false, // as fasthttp doesn't include its own Recovery handler. Repanic bool // WaitForDelivery configures whether you want to block the request before moving forward with the response. // Because fasthttp doesn't include its own `Recovery` handler, it will restart the application, // and event won't be delivered otherwise. WaitForDelivery bool // Timeout for the event delivery requests. Timeout time.Duration ``` -------------------------------- ### Server-Side gRPC with Sentry Interceptor Source: https://github.com/getsentry/sentry-go/blob/master/grpc/README.MD Integrate Sentry's Unary and Stream server interceptors into your gRPC server to automatically capture exceptions and monitor requests. Ensure Sentry is initialized before creating the gRPC server. ```go import ( "fmt" "net" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "github.com/getsentry/sentry-go" sentrygrpc "github.com/getsentry/sentry-go/grpc" ) func main() { // Initialize Sentry if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Create gRPC server with Sentry interceptors server := grpc.NewServer( grpc.UnaryInterceptor(sentrygrpc.UnaryServerInterceptor(sentrygrpc.ServerOptions{ Repanic: true, })), grpc.StreamInterceptor(sentrygrpc.StreamServerInterceptor(sentrygrpc.ServerOptions{ Repanic: true, })), ) // Register reflection for debugging reflection.Register(server) // Start the server listener, err := net.Listen("tcp", ":50051") if err != nil { sentry.CaptureException(err) fmt.Printf("Failed to listen: %v\n", err) return } fmt.Println("Server running...") if err := server.Serve(listener); err != nil { sentry.CaptureException(err) } } ``` -------------------------------- ### Generate Changelog Entries Source: https://github.com/getsentry/sentry-go/blob/master/CONTRIBUTING.md Generate a list of Git commits since the last tag, formatted for the CHANGELOG.md file. This helps in documenting changes for a new release. ```console $ git log --no-merges --format=%s $(git describe --abbrev=0).. | sed 's/^/- /' ``` -------------------------------- ### Enhancing Sentry Events with Middleware Source: https://github.com/getsentry/sentry-go/blob/master/http/README.md Create a middleware function that retrieves the Sentry Hub from the request context and modifies its scope before the main handler is executed. This allows for adding request-specific tags or data. ```go func enhanceSentryEvent(handler http.HandlerFunc) http.HandlerFunc { return func(rw http.ResponseWriter, r *http.Request) { if hub := sentry.GetHubFromContext(r.Context()); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } handler(rw, r) } } ``` -------------------------------- ### Access Request in BeforeSend Callback Source: https://github.com/getsentry/sentry-go/blob/master/iris/README.md Access the original http.Request within the BeforeSend callback during Sentry initialization by checking the hint's context for sentry.RequestContextKey. ```go sentry.Init(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 here } } return event }, }) ``` -------------------------------- ### Access Fiber Context in BeforeSend Callback Source: https://github.com/getsentry/sentry-go/blob/master/fiber/README.md Access the Fiber `Ctx` within the `BeforeSend` callback during Sentry initialization if the event originated from a panic, allowing access to request details. ```go sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event { if hint.Context != nil { if ctx, ok := hint.Context.Value(sentry.RequestContextKey).(*fiber.Ctx); ok { // You have access to the original Context if it panicked fmt.Println(ctx.Hostname()) } } return event }, }) ``` -------------------------------- ### Attribute Builders in Go Source: https://github.com/getsentry/sentry-go/blob/master/CLAUDE.md Use these type-safe builders for structured logging and metrics within the Sentry Go SDK. They are part of the attribute package. ```go attribute.String("key", "value") attribute.Int("count", 42) attribute.Float64("ratio", 0.5) attribute.Bool("flag", true) ``` -------------------------------- ### Client-Side gRPC with Sentry Interceptor Source: https://github.com/getsentry/sentry-go/blob/master/grpc/README.MD Add Sentry's Unary and Stream client interceptors to your gRPC client to monitor outgoing requests. Ensure Sentry is initialized before establishing the gRPC connection. ```go import ( "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/getsentry/sentry-go" sentrygrpc "github.com/getsentry/sentry-go/grpc" ) func main() { // Initialize Sentry if err := sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", }); err != nil { fmt.Printf("Sentry initialization failed: %v\n", err) } // Create gRPC client with Sentry interceptors conn, err := grpc.NewClient( "localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithUnaryInterceptor(sentrygrpc.UnaryClientInterceptor()), grpc.WithStreamInterceptor(sentrygrpc.StreamClientInterceptor()), ) if err != nil { sentry.CaptureException(err) fmt.Printf("Failed to connect: %v\n", err) return } defer conn.Close() client := NewYourServiceClient(conn) // Make a request _, err = client.YourMethod(context.Background(), &YourRequest{}) if err != nil { sentry.CaptureException(err) fmt.Printf("Error calling method: %v\n", err) } } ``` -------------------------------- ### Access Hub and Set Tags in Middleware Source: https://github.com/getsentry/sentry-go/blob/master/iris/README.md Access the Sentry Hub from the Iris context in middleware to set tags and capture messages. Ensure this middleware is attached after the sentryiris handler. ```go app := iris.Default() app.Use(sentryiris.New(sentryiris.Options{ Repanic: true, })) app.Use(func(ctx iris.Context) { if hub := sentryiris.GetHubFromContext(ctx); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } ctx.Next() }) app.Get("/", func(ctx iris.Context) { if hub := sentryiris.GetHubFromContext(ctx); hub != nil { hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } }) app.Get("/foo", func(ctx iris.Context) { // sentryiris handler will catch it just fine. Also, because we attached "someRandomTag" // in the middleware before, it will be sent through as well panic("y tho") }) app.Run(iris.Addr(":3000")) ``` -------------------------------- ### Accessing Sentry Hub in Gin Context Source: https://github.com/getsentry/sentry-go/blob/master/gin/README.md Access the Sentry Hub from the Gin context using sentrygin.GetHubFromContext() in middleware or routes. This allows for request-specific Sentry operations. ```go app := gin.Default() app.Use(sentrygin.New(sentrygin.Options{ Repanic: true, })) app.Use(func(ctx *gin.Context) { if hub := sentrygin.GetHubFromContext(ctx); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } ctx.Next() }) app.GET("/", func(ctx *gin.Context) { if hub := sentrygin.GetHubFromContext(ctx); hub != nil { hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } ctx.Status(http.StatusOK) }) app.GET("/foo", func(ctx *gin.Context) { // sentrygin handler will catch it just fine. Also, because we attached "someRandomTag" // in the middleware before, it will be sent through as well panic("y tho") }) app.Run(":3000") ``` -------------------------------- ### Enhance Sentry Events with Context Source: https://github.com/getsentry/sentry-go/blob/master/fiber/README.md Access the Sentry Hub from the request context to set tags or capture messages specific to the request. This hub should be used instead of global Sentry calls. ```go // Later in the code sentryHandler := sentryfiber.New(sentryfiber.Options{ Repanic: true, WaitForDelivery: true, }) enhanceSentryEvent := func(ctx *fiber.Ctx) { if hub := sentryfiber.GetHubFromContext(ctx); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } ctx.Next() } app := fiber.New() app.Use(sentryHandler) app.All("/foo", enhanceSentryEvent, func(ctx *fiber.Ctx) { panic("y tho") }) app.All("/", func(ctx *fiber.Ctx) { if hub := sentryfiber.GetHubFromContext(ctx); hub != nil { hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } ctx.Status(fiber.StatusOK) }) app.Listen(":3000") ``` -------------------------------- ### Access fasthttp Context in BeforeSend Callback Source: https://github.com/getsentry/sentry-go/blob/master/fasthttp/README.md Access the fasthttp RequestCtx within the BeforeSend callback during Sentry event initialization. This allows inspecting request details when an event occurs. ```go sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event { if hint.Context != nil { if ctx, ok := hint.Context.Value(sentry.RequestContextKey).(*fasthttp.RequestCtx); ok { // You have access to the original Context if it panicked fmt.Println(string(ctx.Request.Host())) } } return event }, }) ``` -------------------------------- ### Commit Attribution Format Source: https://github.com/getsentry/sentry-go/blob/master/AGENTS.md AI commits must include this Co-Authored-By tag. ```text Co-Authored-By: ``` -------------------------------- ### Access Fiber Context in BeforeSend Callback Source: https://github.com/getsentry/sentry-go/blob/master/fiberv3/README.md Access the Fiber context within Sentry's BeforeSend callback to enrich event data with request-specific information. This allows for context-aware event processing. ```go sentry.Init(sentry.ClientOptions{ Dsn: "your-public-dsn", BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event { if hint.Context != nil { if ctx, ok := hint.Context.Value(sentry.RequestContextKey).(fiber.Ctx); ok { fmt.Println(ctx.Hostname()) } } return event }, }) ``` -------------------------------- ### Access Sentry Hub from Request Context Source: https://github.com/getsentry/sentry-go/blob/master/negroni/README.md Access the Sentry Hub from the request context in middleware or routes to set tags or capture messages. This Hub is attached by the sentrynegroni handler. ```go app := negroni.Classic() app.Use(sentrynegroni.New(sentrynegroni.Options{ Repanic: true, })) app.Use(negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { hub := sentry.GetHubFromContext(r.Context()) hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") next(rw, r) })) mux := http.NewServeMux() mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { hub := sentry.GetHubFromContext(r.Context()) hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) rw.WriteHeader(http.StatusOK) }) mux.HandleFunc("/foo", func(rw http.ResponseWriter, r *http.Request) { // sentrynagroni handler will catch it just fine. Also, because we attached "someRandomTag" // in the middleware before, it will be sent through as well panic("y tho") }) app.UseHandler(mux) http.ListenAndServe(":3000", app) ``` -------------------------------- ### Enhance Sentry Event with Context Data Source: https://github.com/getsentry/sentry-go/blob/master/fasthttp/README.md Access the Sentry Hub from the request context to add custom tags or capture messages specific to the request. This ensures data separation between requests. ```go func enhanceSentryEvent(handler fasthttp.RequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } handler(ctx) } } // Later in the code sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{ Repanic: true, WaitForDelivery: true, }) defaultHandler := func(ctx *fasthttp.RequestCtx) { if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil { hub.WithScope(func(scope *sentry.Scope) { scope.SetTag("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } ctx.SetStatusCode(fasthttp.StatusOK) } fooHandler := enhanceSentryEvent(func(ctx *fasthttp.RequestCtx) { panic("y tho") }) fastHTTPHandler := func(ctx *fasthttp.RequestCtx) { switch string(ctx.Path()) { case "/foo": fooHandler(ctx) default: defaultHandler(ctx) } } fmt.Println("Listening and serving HTTP on :3000") if err := fasthttp.ListenAndServe(":3000", sentryHandler.Handle(fastHTTPHandler)); err != nil { panic(err) } ``` -------------------------------- ### Setting Default Tags Source: https://github.com/getsentry/sentry-go/blob/master/logrus/README.md Add default tags to all events sent to Sentry. ```go sentryHook.AddTags(map[string]string{ "key": "value", }) ``` -------------------------------- ### Using hubProvider for Scoped Sentry Hubs Source: https://github.com/getsentry/sentry-go/blob/master/logrus/README.md Set a custom hubProvider function to use a specific Sentry hub for scoped logs. ```go sentryHook.SetHubProvider(func() *sentry.Hub { // Create or return a specific Sentry hub return sentry.NewHub(sentry.GetCurrentHub().Client(), sentry.NewScope()) }) ``` -------------------------------- ### Fallback Functionality Source: https://github.com/getsentry/sentry-go/blob/master/logrus/README.md Configure a fallback function to handle errors during log transmission. ```go sentryHook.Fallback = func(entry *logrus.Entry, err error) { // Handle error } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.