diff --git a/docs/platforms/go/common/configuration/options.mdx b/docs/platforms/go/common/configuration/options.mdx index 28d0ee778c9de..a71d00ea3871f 100644 --- a/docs/platforms/go/common/configuration/options.mdx +++ b/docs/platforms/go/common/configuration/options.mdx @@ -23,6 +23,8 @@ type ClientOptions struct { // 0.0 is treated as if it was 1.0. To drop all events, set the DSN to the // empty string. SampleRate float64 + // Enable structured logging. + EnableLogs bool // Enable performance tracing. EnableTracing bool // The sample rate for sampling traces in the range [0.0, 1.0]. @@ -129,15 +131,6 @@ By default, TLS uses the host's root CA set. If you don't have `ca-certificates` ```go -package main - -import ( - "log" - - "github.com/certifi/gocertifi" - "github.com/getsentry/sentry-go" -) - sentryClientOptions := sentry.ClientOptions{ Dsn: "___PUBLIC_DSN___", } diff --git a/docs/platforms/go/common/configuration/transports.mdx b/docs/platforms/go/common/configuration/transports.mdx index 48ae921d6aff9..c58682c86f123 100644 --- a/docs/platforms/go/common/configuration/transports.mdx +++ b/docs/platforms/go/common/configuration/transports.mdx @@ -14,23 +14,13 @@ To configure transport, provide an instance of `sentry.Transport` interface to ` ```go -package main +sentrySyncTransport := sentry.NewHTTPSyncTransport() +sentrySyncTransport.Timeout = time.Second * 3 -import ( - "time" - - "github.com/getsentry/sentry-go" -) - -func main() { - sentrySyncTransport := sentry.NewHTTPSyncTransport() - sentrySyncTransport.Timeout = time.Second * 3 - - sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - Transport: sentrySyncTransport, - }) -} +sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + Transport: sentrySyncTransport, +}) ``` Each transport, provide it's own factory function. `NewHTTPTransport` and `NewHTTPSyncTransport` respectively. diff --git a/docs/platforms/go/common/index.mdx b/docs/platforms/go/common/index.mdx index 9035e301690e5..4179c4a200eee 100644 --- a/docs/platforms/go/common/index.mdx +++ b/docs/platforms/go/common/index.mdx @@ -10,20 +10,6 @@ Check out the other SDKs we support in the left-hand dropdown. * If you don't have an account and Sentry project established already, please head over to [Sentry](https://sentry.io/signup/), and then return to this page. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - - - ## Install diff --git a/docs/platforms/go/common/integrations/index.mdx b/docs/platforms/go/common/integrations/index.mdx index b3d16ec6e0f6e..c551c045be001 100644 --- a/docs/platforms/go/common/integrations/index.mdx +++ b/docs/platforms/go/common/integrations/index.mdx @@ -12,7 +12,7 @@ To disable default integrations, you can provide an empty list of integrations w ```go sentry.Init(sentry.ClientOptions{ - Dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", + Dsn: "___PUBLIC_DSN___", Integrations: func(i []sentry.Integration) []sentry.Integration { return []sentry.Integration{} }, diff --git a/docs/platforms/go/guides/echo/index.mdx b/docs/platforms/go/guides/echo/index.mdx index a210da1475ab5..c083f518b7e04 100644 --- a/docs/platforms/go/guides/echo/index.mdx +++ b/docs/platforms/go/guides/echo/index.mdx @@ -7,79 +7,25 @@ For a quick reference, there is a [complete example](https://github.com/getsentr [Go Dev-style API documentation](https://pkg.go.dev/github.com/getsentry/sentry-go/echo) is also available. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - ## Install - - ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/echo ``` +## Configure -```go -import ( - "fmt" - "net/http" - - "github.com/getsentry/sentry-go" - sentryecho "github.com/getsentry/sentry-go/echo" - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" -) - -// To initialize Sentry's handler, you need to initialize Sentry itself beforehand -if err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); 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!") -}) +### Initialize the Sentry SDK -// And run it -app.Logger.Fatal(app.Start(":3000")) -``` + -## Configure +### Options `sentryecho` accepts a struct of `Options` that allows you to configure how the handler will behave. -Currently it respects 3 options: - ```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. @@ -92,6 +38,41 @@ WaitForDelivery bool Timeout time.Duration ``` + + +```go +app := echo.New() +app.Use(sentryecho.New(sentryecho.Options{ + // you can modify these options + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +})) +``` + +## Verify + +```go +app := echo.New() +app.Use(middleware.Logger()) +app.Use(middleware.Recover()) + +// Attach the sentryecho handler as one of your middlewares +app.Use(sentryecho.New(sentryecho.Options{ +// specify options here... +})) + +// Set up routes +app.GET("/", func(ctx echo.Context) error { + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + return ctx.String(http.StatusOK, "Hello, World!") +}) + +app.Logger.Fatal(app.Start(":3000")) +``` + ## Usage `sentryecho` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the `echo.Context`, which makes it available throughout the rest of the request's lifetime. diff --git a/docs/platforms/go/guides/fasthttp/index.mdx b/docs/platforms/go/guides/fasthttp/index.mdx index 1e6f9231ab2c4..167a91fb81527 100644 --- a/docs/platforms/go/guides/fasthttp/index.mdx +++ b/docs/platforms/go/guides/fasthttp/index.mdx @@ -7,60 +7,62 @@ For a quick reference, there is a [complete example](https://github.com/getsentr [Go Dev-style API documentation](https://pkg.go.dev/github.com/getsentry/sentry-go/fasthttp) is also available. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - ## Install - - -```shell +```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/fasthttp ``` +## Configure + +### Initialize the Sentry SDK + + + +### Options + +`sentryfasthttp` accepts a struct of `Options` that allows you to configure how the handler will behave. ```go -import ( - "fmt" - "net/http" +// Repanic configures whether Sentry should repanic after recovery, in most cases, it defaults 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 the event won't be delivered otherwise. +WaitForDelivery bool +// Timeout for the event delivery requests. +Timeout time.Duration +``` - "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: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - EnableTracing: true, - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", err) -} +```go +// Create an instance of sentryfasthttp +sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{ + Repanic: false, + WaitForDelivery: true, + Timeout: 5 * time.Second, +}) +``` +## Verify + +```go // Create an instance of sentryfasthttp -sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{}) +sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{ +// specify options here... +}) // After creating the instance, you can attach the handler as one of your middleware fastHTTPHandler := sentryHandler.Handle(func(ctx *fasthttp.RequestCtx) { - panic("y tho") + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + ctx.SetStatusCode(fasthttp.StatusOK) }) fmt.Println("Listening and serving HTTP on :3000") @@ -71,24 +73,6 @@ if err := fasthttp.ListenAndServe(":3000", fastHTTPHandler); err != nil { } ``` -## Configure - -`sentryfasthttp` accepts a struct of `Options` that allows you to configure how the handler will behave. - -Currently, it respects three options: - -```go -// Repanic configures whether Sentry should repanic after recovery, in most cases, it defaults 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 the event won't be delivered otherwise. -WaitForDelivery bool -// Timeout for the event delivery requests. -Timeout time.Duration -``` - ## Usage `sentryfasthttp` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the request's context, which makes it available throughout the rest of the request's lifetime. diff --git a/docs/platforms/go/guides/fiber/index.mdx b/docs/platforms/go/guides/fiber/index.mdx index afea6ab5bca7b..3a3128125ad7c 100644 --- a/docs/platforms/go/guides/fiber/index.mdx +++ b/docs/platforms/go/guides/fiber/index.mdx @@ -3,96 +3,29 @@ title: Fiber description: "Learn how to add Sentry instrumentation to programs using the Fiber package." --- -The Sentry Go SDK repository has a [complete -example](https://github.com/getsentry/sentry-go/tree/master/_examples/fiber) -of how to set up Sentry for a Fiber app. +For a quick reference, there is a [complete example](https://github.com/getsentry/sentry-go/tree/master/_examples/fiber) at the Go SDK source code repository. -For additional reference, see the [`sentryfiber` API -documentation](https://godoc.org/github.com/getsentry/sentry-go/fiber). +[Go Dev-style API documentation](https://godoc.org/github.com/getsentry/sentry-go/fiber) is also available. ## Install - - -```shell +```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/fiber ``` -```go -import ( - "fmt" - "net/http" - - "github.com/getsentry/sentry-go" - sentryfiber "github.com/getsentry/sentry-go/fiber" -) - -// To initialize Sentry's handler, you need to initialize Sentry itself beforehand -if err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - EnableTracing: true, - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for performance monitoring. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", err) -} - - // Later in the code - sentryHandler := sentryfiber.New(sentryfiber.Options{ - Repanic: true, - WaitForDelivery: true, - }) - - enhanceSentryEvent := func(ctx *fiber.Ctx) error { - if hub := sentryfiber.GetHubFromContext(ctx); hub != nil { - hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") - } - return ctx.Next() - } - - app := fiber.New() - - app.Use(sentryHandler) - - app.All("/foo", enhanceSentryEvent, func(c *fiber.Ctx) error { - panic("y tho") - }) +## Configure - app.All("/", func(ctx *fiber.Ctx) error { - if hub := sentryfiber.GetHubFromContext(ctx); hub != nil { - hub.WithScope(func(scope *sentry.Scope) { - scope.SetExtra("unwantedQuery", "someQueryDataMaybe") - hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") - }) - } - return ctx.SendStatus(fiber.StatusOK) - }) +### Initialize the Sentry SDK - if err := app.Listen(":3000"); err != nil { - panic(err) - } -``` + -## Configure +### Options `sentryfiber` accepts a struct of `Options` that allows you to configure how the handler will behave. -Currently, it respects three options: - ```go // Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true, // as fiber includes its own Recover middleware that handles http responses. @@ -105,6 +38,41 @@ WaitForDelivery bool Timeout time.Duration ``` + + +```go +sentryHandler := sentryfiber.New(sentryfiber.Options{ + // you can modify these options + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +}) + +app := fiber.New() +app.Use(sentryHandler) +``` + +## Verify + +```go +app := fiber.New() + +app.Use(sentryfiber.New(sentryfiber.Options{ +// specify options here... +})) + +app.All("/", func(ctx *fiber.Ctx) error { + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + return ctx.SendStatus(fiber.StatusOK) +}) + +if err := app.Listen(":3000"); err != nil { + panic(err) +} +``` + ## Usage `sentryfiber` attaches an instance of `*sentry.Hub` (https://godoc.org/github.com/getsentry/sentry-go#Hub) to the request's context, which makes it available throughout the rest of the request's lifetime. @@ -153,8 +121,6 @@ fmt.Println("Listening and serving HTTP on :3000") ### Accessing Context in `BeforeSend` callback - - ```go sentry.Init(sentry.ClientOptions{ Dsn: "___PUBLIC_DSN___", diff --git a/docs/platforms/go/guides/gin/index.mdx b/docs/platforms/go/guides/gin/index.mdx index 2031baf9b78b5..54e811ceb9148 100644 --- a/docs/platforms/go/guides/gin/index.mdx +++ b/docs/platforms/go/guides/gin/index.mdx @@ -7,76 +7,25 @@ For a quick reference, there is a [complete example](https://github.com/getsentr [Go Dev-style API documentation](https://pkg.go.dev/github.com/getsentry/sentry-go/gin) is also available. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - ## Install - - ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/gin ``` +## Configure -```go -import ( - "fmt" - "net/http" - - sentry "github.com/getsentry/sentry-go" - sentrygin "github.com/getsentry/sentry-go/gin" - "github.com/gin-gonic/gin" -) +### Initialize the Sentry SDK -// To initialize Sentry's handler, you need to initialize Sentry itself beforehand -if err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - EnableTracing: true, - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); 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") -``` - -## Configure +### Options `sentrygin` accepts a struct of `Options` that allows you to configure how the handler will behave. -Currently it respects 3 options: - ```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. @@ -89,6 +38,40 @@ WaitForDelivery bool Timeout time.Duration ``` + + +```go +app := gin.Default() +app.Use(sentrygin.New(sentrygin.Options{ + // you can modify these options + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +})) +``` + +## Verify + +```go +app := gin.Default() + +// you can attach the handler as one of your middleware +app.Use(sentrygin.New(sentrygin.Options{ +// specify options here... +})) + +// Set up routes +app.GET("/", func(ctx *gin.Context) { + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + ctx.String(http.StatusOK, "Hello world!") +}) + +// And run it +app.Run(":3000") +``` + ## Usage `sentrygin` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the `*gin.Context`, which makes it available throughout the rest of the request's lifetime. diff --git a/docs/platforms/go/guides/http/index.mdx b/docs/platforms/go/guides/http/index.mdx index 2a76d03f495c5..bf03bbb552308 100644 --- a/docs/platforms/go/guides/http/index.mdx +++ b/docs/platforms/go/guides/http/index.mdx @@ -7,62 +7,66 @@ For a quick reference, there is a [complete example](https://github.com/getsentr [Go Dev-style API documentation](https://pkg.go.dev/github.com/getsentry/sentry-go/http) is also available. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - ## Install - - ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/http ``` +## Configure + +### Initialize the Sentry SDK + + + +### Options + +`sentryhttp` accepts a struct of `Options` that allows you to configure how the handler will behave. ```go -import ( - "fmt" - "net/http" +// Whether Sentry should repanic after recovery, in most cases it should be set to true, +// and you should gracefully handle http responses. +Repanic bool +// Whether you want to block the request before moving forward with the response. +// Useful, when you want to restart the process after it panics. +WaitForDelivery bool +// Timeout for the event delivery requests. +Timeout time.Duration +``` - "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: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - EnableTracing: true, - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", err) +```go +// Create an instance of sentryhttp +sentryHandler := sentryhttp.New(sentryhttp.Options{ + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +}) +``` + +## Verify + +```go +type handler struct{} + +func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + rw.WriteHeader(http.StatusOK) } // Create an instance of sentryhttp -sentryHandler := sentryhttp.New(sentryhttp.Options{}) +sentryHandler := sentryhttp.New(sentryhttp.Options{ +// specify options here... +}) // Once it's done, you can set up 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") @@ -72,23 +76,6 @@ if err := http.ListenAndServe(":3000", nil); err != nil { } ``` -## Configure - -`sentryhttp` accepts a struct of `Options` that allows you to configure how the handler will behave. - -Currently it respects 3 options: - -```go -// Whether Sentry should repanic after recovery, in most cases it should be set to true, -// and you should gracefully handle http responses. -Repanic bool -// Whether you want to block the request before moving forward with the response. -// Useful, when you want to restart the process after it panics. -WaitForDelivery bool -// Timeout for the event delivery requests. -Timeout time.Duration -``` - ## Usage `sentryhttp` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the request's context, which makes it available throughout the rest of the request's lifetime. diff --git a/docs/platforms/go/guides/iris/index.mdx b/docs/platforms/go/guides/iris/index.mdx index 4559e3a746cc8..473b819039f39 100644 --- a/docs/platforms/go/guides/iris/index.mdx +++ b/docs/platforms/go/guides/iris/index.mdx @@ -7,78 +7,28 @@ For a quick reference, there is a [complete example](https://github.com/getsentr [Go Dev-style API documentation](https://pkg.go.dev/github.com/getsentry/sentry-go/iris) is also available. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - ## Install - - ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/iris ``` +## Configure -```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: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - EnableTracing: true, - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); 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!") -}) +### Initialize the Sentry SDK -// And run it -app.Run(iris.Addr(":3000")) -``` + -## Configure +### Options `sentryiris` accepts a struct of `Options` that allows you to configure how the handler will behave. -Currently it respects 3 options: - ```go // Whether Sentry should repanic after recovery, in most cases it should be set to true, -// as iris.Default includes its own Recovery middleware what handles http responses. +// 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, @@ -88,6 +38,41 @@ WaitForDelivery bool Timeout time.Duration ``` + + +```go +app := iris.Default() +app.Use(sentryiris.New(sentryiris.Options{ + // modify your own config options + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +})) +``` + +## Verify + +```go +// 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{ +// specify options here... +})) + +// Set up routes +app.Get("/", func(ctx iris.Context) { + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + ctx.Writef("Hello world!") +}) + +// And run it +app.Run(iris.Addr(":3000")) +``` + ## Usage `sentryiris` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the `iris.Context`, which makes it available throughout the rest of the request's lifetime. diff --git a/docs/platforms/go/guides/logrus/index.mdx b/docs/platforms/go/guides/logrus/index.mdx index 3a339e3daa62c..b05fcec5dcba4 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -14,126 +14,133 @@ Logrus structured logging is supported in Sentry Go SDK version `0.34.0` and abo ## Install ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/logrus ``` - +## Configure + +### Initialize the Sentry SDK + + - +### Options + +`sentrylogrus` provides two types of hooks to configure the integration with Sentry. Both hooks accept these options: +- **Levels**: A slice of `logrus.Level` specifying which log levels to capture +- **ClientOptions**: Standard `sentry.ClientOptions` for configuration + +## Verify To integrate Sentry with Logrus, you can set up both log hooks and event hooks to capture different types of data at various log levels. ```go -import ( - "fmt" - "net/http" - "os" - "time" - - "github.com/sirupsen/logrus" - "github.com/getsentry/sentry-go" - sentrylogrus "github.com/getsentry/sentry-go/logrus" -) +// Initialize Sentry SDK +if err := sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + EnableLogs: true, +}); err != nil { + log.Fatalf("Sentry initialization failed: %v", err) +} + +logger := logrus.New() +logger.Level = logrus.DebugLevel +logger.Out = os.Stderr -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: "___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 - EnableLogs: 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: "___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 - }, - 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") +// Get the Sentry client from the current hub +hub := sentry.CurrentHub() +client := hub.Client() +if client == nil { + log.Fatalf("Sentry client is nil") } -``` -## Configure +// Create log hook to send logs on Info level +logHook := sentrylogrus.NewLogHookFromClient( + []logrus.Level{logrus.InfoLevel}, + client, +) -`sentrylogrus` provides two types of hooks to configure the integration with Sentry. Both hooks accept these options: -- **Levels**: A slice of `logrus.Level` specifying which log levels to capture -- **ClientOptions**: Standard `sentry.ClientOptions` for configuration +// Create event hook to send events on Error, Fatal, Panic levels +eventHook := sentrylogrus.NewEventHookFromClient( + []logrus.Level{ + logrus.ErrorLevel, + logrus.FatalLevel, + logrus.PanicLevel, + }, + client, +) + +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) +}) + +// Info level is sent as a log to Sentry +logger.Infof("Application has started") + +// Example of logging with attributes +logger.WithField("user", "test-user").Error("An error occurred") + +// Error level is sent as an error event to Sentry +logger.Errorf("oh no!") + +// Fatal level is sent as an error event to Sentry and terminates the application +logger.Fatalf("can't continue...") +``` ### LogHook -Use `sentrylogrus.NewLogHook()` to send structured logs to Sentry. This hook captures log entries and sends them to Sentry's structured logging system. +You have two ways to create a new `LogHook`. Either by using `sentrylogrus.NewLogHook()` and passing the `sentry.ClientOptions`, or +by using `sentrylogrus.NewLogHookFromClient()` and passing an already created `sentry.Client`. These hook captures log entries and +send them to Sentry's structured logging system. +#### NewLogHook ```go logHook, err := sentrylogrus.NewLogHook( []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, sentry.ClientOptions{ Dsn: "___PUBLIC_DSN___", EnableLogs: true, // Required for log entries - }) + }, +) +``` + +#### NewLogHookFromClient + +Use `NewLogHookFromClient` if you've already initialized the Sentry SDK. +```go +if err := sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + EnableLogs: true, +}); err != nil { + log.Fatalf("Sentry initialization failed: %v", err) +} +hub := sentry.CurrentHub() +client := hub.Client() +if client != nil { + logHook := sentrylogrus.NewLogHookFromClient( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + client, + ) +} else { + log.Fatalf("Sentrylogrus initialization failed: nil client") +} ``` ### EventHook -Use `sentrylogrus.NewEventHook()` to send log entries as Sentry events. This is useful for error tracking and alerting. +You also have two ways to create a new `EventHook`. Either by using `sentrylogrus.NewEventHook()` and passing the `sentry.ClientOptions`, or +by using `sentrylogrus.NewEventFromClient()` and passing an already created `sentry.Client`. These hook captures log entries and +send them as events. This is helpful for error tracking and alerting. +#### NewEventHook ```go eventHook, err := sentrylogrus.NewEventHook( []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}, @@ -141,36 +148,36 @@ eventHook, err := sentrylogrus.NewEventHook( Dsn: "___PUBLIC_DSN___", Debug: true, AttachStacktrace: true, - }) + }, +) +``` +#### NewEventHookFromClient + +Use `NewEventHookFromClient` if you've already initialized the Sentry SDK. +```go +if err := sentry.Init(sentry.ClientOptions{ + Dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", + EnableLogs: true, +}); err != nil { + log.Fatalf("Sentry initialization failed: %v", err) +} +hub := sentry.CurrentHub() +client := hub.Client() +if client != nil { + eventHook := sentrylogrus.NewEventHookFromClient( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + client, + ) +} else { + log.Fatalf("Sentrylogrus initialization failed: nil client") +} ``` When using both hooks, ensure you flush both of them before the application exits and register exit handlers for fatal logs to avoid losing pending events. -## Correlating Logs with Traces - -To correlate logs with transactions, you need to pass a `context.Context` that contains transaction information to your logger calls. The `sentryhttp` middleware automatically adds transaction information to the request's context. -Here's an example of how to use `WithContext` in an HTTP handler to ensure logs are associated with the correct trace. - -```go -// Assume logger is initialized and Sentry hooks are added as shown above. -// var logger *logrus.Logger - -func myAsyncHandler(w http.ResponseWriter, r *http.Request) { - // The sentryhttp middleware adds a Hub with transaction information to the request context. - ctx := r.Context() - // By using WithContext, the log entry will be associated with the transaction from the request. - logger.WithContext(ctx).Info("Log inside handler") - w.WriteHeader(http.StatusOK) - fmt.Fprintln(w, "Handler finished, async task running in background.") -} - -// In your main function, or wherever you set up your routes: -// Wrap your handler with sentryhttp to automatically start transactions for requests. -sentryHandler := sentryhttp.New(sentryhttp.Options{}) -http.Handle("/async", sentryHandler.Handle(http.HandlerFunc(myAsyncHandler))) -``` + ## Logs diff --git a/docs/platforms/go/guides/negroni/index.mdx b/docs/platforms/go/guides/negroni/index.mdx index 6b3f3076def15..7138f898e95ae 100644 --- a/docs/platforms/go/guides/negroni/index.mdx +++ b/docs/platforms/go/guides/negroni/index.mdx @@ -7,66 +7,67 @@ For a quick reference, there is a [complete example](https://github.com/getsentr [Go Dev-style API documentation](https://pkg.go.dev/github.com/getsentry/sentry-go/negroni) is also available. -## Features - -In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). - -Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below. - ## Install - - ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/negroni ``` +## Configure + +### Initialize the Sentry SDK + + + +### Options + +`sentrynegroni` accepts a struct of `Options` that allows you to configure how the handler will behave. ```go -import ( - "fmt" - "net/http" +// 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 +``` - "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: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - EnableTracing: true, - // Set TracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production, - TracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, -}); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", err) -} - -// Then create your app +```go +app := negroni.Classic() + +app.Use(sentrynegroni.New(sentrynegroni.Options{ + // modify your own config options + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +})) +``` + +## Verify + +```go app := negroni.Classic() -// Once it's done, you can attach the handler as one of your middleware -app.Use(sentrynegroni.New(sentrynegroni.Options{})) +app.Use(sentrynegroni.New(sentrynegroni.Options{ +// specify options here... +})) // Set up routes mux := http.NewServeMux() mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello world!") + // capturing an error intentionally to simulate usage + sentry.CaptureMessage("It works!") + + fmt.Fprintf(rw, "Hello world!") }) app.UseHandler(mux) @@ -75,24 +76,6 @@ app.UseHandler(mux) http.ListenAndServe(":3000", app) ``` -## Configure - -`sentrynegroni` accepts a struct of `Options` that allows you to configure how the handler will behave. - -Currently it respects 3 options: - -```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 -``` - ## Usage `sentrynegroni` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the request's context, which makes it available throughout the rest of the request's lifetime. diff --git a/docs/platforms/go/guides/slog/index.mdx b/docs/platforms/go/guides/slog/index.mdx index 56a82ef287221..fc8edfa8cafdc 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -14,177 +14,76 @@ Slog structured logging is supported in Sentry Go SDK version `0.34.0` and above ## Install ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/slog ``` - - - - -To integrate Sentry with slog, you need to set up a Sentry handler and configure the Sentry client. - -```go -import ( - "context" - "fmt" - "log" - "time" - - "log/slog" - - "github.com/getsentry/sentry-go" - sentryslog "github.com/getsentry/sentry-go/slog" -) - -func main() { - // Initialize Sentry - err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - EnableTracing: false, - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, - EnableLogs: true, - }) - if err != nil { - log.Fatal(err) - } - defer sentry.Flush(2 * time.Second) - - // Configure `slog` to use Sentry as a handler - ctx := context.Background() - handler := sentryslog.Option{ - EventLevel: []slog.Level{slog.LevelError}, // Only Error level will be sent as events - LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Only Warn and Info levels will be sent as logs - }.NewSentryHandler(ctx) - logger := slog.New(handler) - logger = logger.With("release", "v1.0.0") - - // Log messages with various attributes - logger. - With( - slog.Group("user", - slog.String("id", "user-123"), - slog.Time("created_at", time.Now()), - ), - ). - With("environment", "dev"). - With("error", fmt.Errorf("an error")). - ErrorContext(ctx, "a message") -} -``` - ## Configure -`sentryslog` provides options to configure the integration with Sentry. It accepts a struct of `sentryslog.Options` that allows you to configure how the handler will behave. The options are: - -```go -// EventLevel specifies the exact log levels to capture and send to Sentry as Events. -// Only logs at these specific levels will be processed as events. -// Defaults to []slog.Level{slog.LevelError, LevelFatal}. -EventLevel slog.Leveler -// LogLevel specifies the exact log levels to capture and send to Sentry as Log entries -// Only logs at these specific levels will be processed as log entries. -// Defaults to []slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, LevelFatal}. -LogLevel slog.Leveler -// Hub specifies the Sentry Hub to use for capturing events. -// If not provided, the current Hub is used by default. -Hub *sentry.Hub -// Converter is an optional function that customizes how log records -// are converted into Sentry events. By default, the DefaultConverter is used. -Converter Converter -// AttrFromContext is an optional slice of functions that extract attributes -// from the context. These functions can add additional metadata to the log entry. -AttrFromContext []func(ctx context.Context) []slog.Attr -// AddSource is an optional flag that, when set to true, includes the source -// information (such as file and line number) in the Sentry event. -// This can be useful for debugging purposes. -AddSource bool -// ReplaceAttr is an optional function that allows for the modification or -// replacement of attributes in the log record. This can be used to filter -// or transform attributes before they are sent to Sentry. -ReplaceAttr func(groups []string, a slog.Attr) slog.Attr -``` - -## Usage +### Initialize the Sentry SDK -### Sending Logs vs Events + -Sentry allows you to send logs either as log entries or as events. The minimum log level defaults to `slog.LevelDebug` and logs will be sent if the `EnableLogs` option is set. The minimum event level defaults to `slog.LevelError`. +### Options -### Example: Sending Logs as Events +`sentryslog` provides options to configure the integration with Sentry. It accepts a struct of `sentryslog.Options` that allows you to configure how the handler will behave. The options are: ```go -ctx := context.Background() -logger := slog.New(sentryslog.Option{ - // specify all event levels - EventLevel: []slog.Level{ - slog.LevelDebug, - slog.LevelInfo, - slog.LevelWarn, - slog.LevelError, - }, - LogLevel: []slog.Level{}, // disable log entries - AttrFromContext: []func(ctx context.Context) []slog.Attr{ - func(ctx context.Context) []slog.Attr { - return []slog.Attr{slog.String("request_id", "123")} - }, - }, -}.NewSentryHandler(ctx)) - -logger.Error("This log is sent as an event") +type Option struct { + // EventLevel specifies the exact log levels to capture and send to Sentry as Events. + // Only logs at these specific levels will be processed as events. + // Defaults to []slog.Level{slog.LevelError, LevelFatal}. + EventLevel []slog.Level + + // LogLevel specifies the exact log levels to capture and send to Sentry as Log entries. + // Only logs at these specific levels will be processed as log entries. + // Defaults to []slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, LevelFatal}. + LogLevel []slog.Level + + // Hub specifies the Sentry Hub to use for capturing events. + // If not provided, the current Hub is used by default. + Hub *sentry.Hub + + // Converter is an optional function that customizes how log records + // are converted into Sentry events. By default, the DefaultConverter is used. + Converter Converter + + // AttrFromContext is an optional slice of functions that extract attributes + // from the context. These functions can add additional metadata to the log entry. + AttrFromContext []func(ctx context.Context) []slog.Attr + + // AddSource is an optional flag that, when set to true, includes the source + // information (such as file and line number) in the Sentry event. + // This can be useful for debugging purposes. + AddSource bool + + // ReplaceAttr is an optional function that allows for the modification or + // replacement of attributes in the log record. This can be used to filter + // or transform attributes before they are sent to Sentry. + ReplaceAttr func(groups []string, a slog.Attr) slog.Attr +} ``` -### Example: Sending Logs as Logs +## Verify ```go +// Configure `slog` to use Sentry as a handler ctx := context.Background() -logger := slog.New(sentryslog.Option{ - EventLevel: []slog.Level{}, // disable events - // specify all log levels - LogLevel: []slog.Level{ - slog.LevelDebug, - slog.LevelInfo, - slog.LevelWarn, - slog.LevelError, - }, -}.NewSentryHandler(ctx)) - -logger.Error("This log is sent as a log") -``` - - - In order to properly attach the correct trace with each Log entry, a - `context.Context` is required. We recommend using `Context` functions to ensure your logs - are connected to spans and errors in the Sentry UI. - - -## Correlating Logs with Traces - -To correlate logs with transactions, you need to pass a `context.Context` that contains transaction information to your logger calls. The `sentryhttp` middleware automatically adds transaction information to the request's context. -Here's an example of how to use `InfoContext` in an HTTP handler to ensure logs are associated with the correct trace. - -```go -// Assume logger is initialized with the Sentry handler as shown above. -// var logger *slog.Logger - -func myAsyncHandler(w http.ResponseWriter, r *http.Request) { - // The sentryhttp middleware adds a Hub with transaction information to the request context. - ctx := r.Context() - // By using InfoContext, the log entry will be associated with the transaction from the request. - slog.InfoContext(ctx, "Log inside handler") - w.WriteHeader(http.StatusOK) - fmt.Fprintln(w, "Handler finished, async task running in background.") -} - -func main() { - // Wrap your handler with sentryhttp to automatically start transactions for requests. - sentryHandler := sentryhttp.New(sentryhttp.Options{}) - http.Handle("/async", sentryHandler.Handle(http.HandlerFunc(myAsyncHandler))) -} +handler := sentryslog.Option{ + // Explicitly specify the levels that you want to be captured. + EventLevel: []slog.Level{slog.LevelError}, // Captures only [slog.LevelError] as error events. + LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Captures only [slog.LevelWarn] and [slog.LevelInfo] as log entries. +}.NewSentryHandler(ctx) +logger := slog.New(handler) + +// Send an error event to Sentry to verify functionality +logger.Error("This error will be sent to Sentry!") + +// Also a log entry +logger.With("key.string", "value").Info("An error occurred") ``` -Note: Ensure Sentry is flushed before the application exits to avoid losing any pending events. + ## Logs diff --git a/docs/platforms/go/guides/zerolog/index.mdx b/docs/platforms/go/guides/zerolog/index.mdx index 32696e70eba01..4966c02d43a80 100644 --- a/docs/platforms/go/guides/zerolog/index.mdx +++ b/docs/platforms/go/guides/zerolog/index.mdx @@ -10,15 +10,73 @@ For a complete example, visit the [Go SDK source code repository](https://github ## Install ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/zerolog ``` - +## Configure -To integrate Sentry with Zerolog, you need to set up a custom writer that sends logs to Sentry based on the configured levels. +### Initialize the Sentry SDK + + + +### Options +sentryzerolog provides options to configure the integration with Sentry. It expects a `sentryzerolog.Config` that has `sentry.ClientOptions` and `sentryzerolog.Options`. +The sentryzerolog.Options struct has the following fields: + +```go +// Levels specifies the log levels that will trigger event sending to Sentry. +// Only log messages at these levels will be sent. By default, the levels are +// Error, Fatal, and Panic. +Levels []zerolog.Level + +// WithBreadcrumbs, when enabled, adds log entries as breadcrumbs in Sentry. +// Breadcrumbs provide a trail of events leading up to an error, which can +// be invaluable for understanding the context of issues. +WithBreadcrumbs bool + +// FlushTimeout sets the maximum duration allowed for flushing events to Sentry. +// This is the time limit within which all pending events must be sent to Sentry +// before the application exits. A typical use is ensuring all logs are sent before +// application shutdown. The default timeout is usually 3 seconds. +FlushTimeout time.Duration +``` + +## Verify + +```go +// Configure Zerolog to use Sentry as a writer +sentryWriter, err := sentryzerolog.New(sentryzerolog.Config{ + ClientOptions: sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + }, + Options: sentryzerolog.Options{ + Levels: []zerolog.Level{zerolog.ErrorLevel, zerolog.FatalLevel, zerolog.PanicLevel}, + WithBreadcrumbs: true, + FlushTimeout: 3 * time.Second, + }, +}) +if err != nil { + log.Fatal().Err(err).Msg("failed to create sentry writer") +} +defer sentryWriter.Close() + +// Use Sentry writer in Zerolog +log.Logger = log.Output(zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr}, sentryWriter)) + +// Test logging - this will be sent to Sentry as an event +log.Error().Msg("This error will be sent to Sentry!") + +// Example of logging with error context +log.Error().Err(errors.New("test error")).Msg("An error occurred") +``` + +## Usage + +To integrate Sentry with Zerolog, you need to set up a custom writer that sends logs to Sentry based on the configured levels. ```go import ( @@ -81,32 +139,8 @@ func main() { } ``` -## Configure - -sentryzerolog provides options to configure the integration with Sentry. It expects a `sentryzerolog.Config` that has `sentry.ClientOptions` and `sentryzerolog.Options`. The `sentry.ClientOptions` are used to initialize the Sentry client, and the `sentryzerolog.Options` are used to configure the Zerolog integration. - -The sentryzerolog.Options struct has the following fields: - - -```go -// Levels specifies the log levels that will trigger event sending to Sentry. -// Only log messages at these levels will be sent. By default, the levels are -// Error, Fatal, and Panic. -Levels []zerolog.Level - -// WithBreadcrumbs, when enabled, adds log entries as breadcrumbs in Sentry. -// Breadcrumbs provide a trail of events leading up to an error, which can -// be invaluable for understanding the context of issues. -WithBreadcrumbs bool -// FlushTimeout sets the maximum duration allowed for flushing events to Sentry. -// This is the time limit within which all pending events must be sent to Sentry -// before the application exits. A typical use is ensuring all logs are sent before -// application shutdown. The default timeout is usually 3 seconds. -FlushTimeout time.Duration -``` - -- Using `hubProvider` for Scoped Sentry Hubs +### 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. @@ -121,7 +155,6 @@ sentryHook.SetHubProvider(func() *sentry.Hub { This ensures that logs from specific contexts or threads use the appropriate Sentry hub and scope. -## Usage Use Zerolog as you normally would, and it will automatically send logs at or above the specified levels to Sentry. diff --git a/includes/logs/go-ctx-usage-alert.mdx b/includes/logs/go-ctx-usage-alert.mdx new file mode 100644 index 0000000000000..effe5480ded43 --- /dev/null +++ b/includes/logs/go-ctx-usage-alert.mdx @@ -0,0 +1,4 @@ +## Correlating Logs With Traces + +In order to properly attach the correct trace with each log entry, a `context.Context` is required. +If you're using logs combined with tracing, you should pass the correct context to properly attach each trace with the appropriate logs. \ No newline at end of file diff --git a/platform-includes/configuration/drain-example/go.mdx b/platform-includes/configuration/drain-example/go.mdx index 56485e5e172f4..f89f5eb7eeb27 100644 --- a/platform-includes/configuration/drain-example/go.mdx +++ b/platform-includes/configuration/drain-example/go.mdx @@ -9,24 +9,20 @@ for at most the given timeout. It returns `false` if the timeout was reached. In that case, some events may not have been sent. ```go -func main() { - // err := sentry.Init(...) - defer sentry.Flush(2 * time.Second) +// err := sentry.Init(...) +defer sentry.Flush(2 * time.Second) - sentry.CaptureMessage("my message") -} +sentry.CaptureMessage("my message") ``` `FlushWithContext` is an alternative to Flush that uses a context.Context to manage the timeout or cancellation of the flush operation. This approach is particularly useful in applications where you are already using contexts for managing deadlines and cancellations. ```go -func main() { - // err := sentry.Init(...) - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - sentry.CaptureMessage("my message") - sentry.FlushWithContext(ctx) -} +// err := sentry.Init(...) +ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) +defer cancel() + +sentry.CaptureMessage("my message") +sentry.FlushWithContext(ctx) ``` diff --git a/platform-includes/getting-started-config/go.mdx b/platform-includes/getting-started-config/go.mdx index 90d3d51b05647..2586a4088de97 100644 --- a/platform-includes/getting-started-config/go.mdx +++ b/platform-includes/getting-started-config/go.mdx @@ -1,41 +1,34 @@ ```go -package main - -import ( - "log" - "time" - - "github.com/getsentry/sentry-go" -) - -func main() { - err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // Enable printing of SDK debug messages. - // Useful when getting started or trying to figure something out. - Debug: true, - // Adds request headers and IP for users, - // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info - SendDefaultPII: true, - // ___PRODUCT_OPTION_START___ logs - - // Enable logs to be sent to Sentry - EnableLogs: true, - // ___PRODUCT_OPTION_END___ logs - }) - if err != nil { - log.Fatalf("sentry.Init: %s", err) - } - // Flush buffered events before the program terminates. - // Set the timeout to the maximum duration the program can afford to wait. - defer sentry.Flush(2 * time.Second) +err := sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + // Enable printing of SDK debug messages. + // Useful when getting started or trying to figure something out. + Debug: true, + // Adds request headers and IP for users, + // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info + SendDefaultPII: true, + // ___PRODUCT_OPTION_START___ performance + EnableTracing: true, + // Set TracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + TracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + // ___PRODUCT_OPTION_START___ logs + EnableLogs: true, + // ___PRODUCT_OPTION_END___ logs +}) +if err != nil { + log.Fatalf("sentry.Init: %s", err) } +// Flush buffered events before the program terminates. +// Set the timeout to the maximum duration the program can afford to wait. +defer sentry.Flush(2 * time.Second) ``` diff --git a/platform-includes/getting-started-include-logs-config/go.mdx b/platform-includes/getting-started-include-logs-config/go.mdx new file mode 100644 index 0000000000000..d0ca781c6d0f3 --- /dev/null +++ b/platform-includes/getting-started-include-logs-config/go.mdx @@ -0,0 +1,31 @@ + + +```go +err := sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + // Enable printing of SDK debug messages. + // Useful when getting started or trying to figure something out. + Debug: true, + // Adds request headers and IP for users, + // visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info + SendDefaultPII: true, + EnableLogs: true, + // ___PRODUCT_OPTION_START___ performance + EnableTracing: true, + // Set TracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + TracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance +}) +if err != nil { + log.Fatalf("sentry.Init: %s", err) +} +// Flush buffered events before the program terminates. +// Set the timeout to the maximum duration the program can afford to wait. +defer sentry.Flush(2 * time.Second) +```