From 9a2a473bd2e734ab4c4355b69cc22ca59a51c237 Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Fri, 4 Jul 2025 11:49:54 +0200 Subject: [PATCH 1/8] restructure Go docs --- docs/platforms/go/common/logs/index.mdx | 167 ++++++++---------- docs/platforms/go/guides/logrus/index.mdx | 89 +++++++--- docs/platforms/go/guides/slog/index.mdx | 199 +++++++--------------- includes/logs/go-ctx-usage-alert.mdx | 4 + 4 files changed, 204 insertions(+), 255 deletions(-) create mode 100644 includes/logs/go-ctx-usage-alert.mdx diff --git a/docs/platforms/go/common/logs/index.mdx b/docs/platforms/go/common/logs/index.mdx index 8909c56716ed2..e37d7573ca579 100644 --- a/docs/platforms/go/common/logs/index.mdx +++ b/docs/platforms/go/common/logs/index.mdx @@ -11,123 +11,101 @@ With Sentry Structured Logs, you can send text based log information from your a ## Requirements -Logs in Go are supported in Sentry Go SDK version `0.33.0` and above. +Logs in Go are supported in Sentry Go SDK version `0.33.0` and above. For using integrations of other log libraries, have a look at each specific page for more details on requirements. ## Setup To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. ```go -package main - -import ( - "context" - "github.com/getsentry/sentry-go" - "time" -) - -func main() { - if err := sentry.Init(sentry.ClientOptions{ +sentry.Init(sentry.ClientOptions{ Dsn: "___PUBLIC_DSN___", + // Enable logs to be sent to Sentry EnableLogs: true, - }); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", 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) -} +}) ``` ## Usage -Once the feature is enabled on the SDK and the SDK is initialized, you can send logs by using -the `sentry.Logger` API. - -The `Sentry.Logger` API exposes methods that support six different log levels: `trace`, -`debug`, `info`, `warn`, `error` and `fatal`. The methods support both `fmt.Print` and `fmt.Printf` like syntax. -If you pass in format specifiers like `%v`, these will be sent to Sentry, and can be searched from within the Logs UI, -and even added to the Logs views as a dedicated column. - -```go -ctx := context.Background() -logger := sentry.NewLogger(ctx) +Once the feature is enabled on the SDK and the SDK is initialized, you can send logs by using the `sentry.Logger` API or our different integrations. -// You can use the logger like [fmt.Print] -logger.Info(ctx, "Hello ", "world!") -// Or like [fmt.Printf] -logger.Infof(ctx, "Hello %v!", "world") -``` +The `sentry.Logger` API exposes methods that support six different log levels: +- `trace` +- `debug` +- `info` +- `warn` +- `error` +- `fatal` -You can also pass additional attributes to the logger via the `SetAttributes` function. These attributes will also be searchable in the Logs UI. +The methods support both `fmt.Print` and `fmt.Printf` like syntax. If you pass in format specifiers like `%v`, these will be +sent to Sentry, and can be searched from within the Logs UI, and even added to the Logs views as a dedicated column. ```go -package main - -import ( - "context" - "github.com/getsentry/sentry-go" - "github.com/getsentry/sentry-go/attribute" - "time" -) - func main() { - err := sentry.Init(sentry.ClientOptions{ + if err := sentry.Init(sentry.ClientOptions{ Dsn: "___PUBLIC_DSN___", EnableLogs: true, - }) - if err != nil { - panic(err) + }); err != nil { + log.Fatalf("Sentry initialization failed: %v", 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) + // The SentryLogger requires context, to link logs with the appropriate traces. You can either create a new logger + // by providing the context, or use WithCtx() to pass the context inline. ctx := context.Background() logger := sentry.NewLogger(ctx) - logger.SetAttributes( - attribute.Int("key.int", 42), - attribute.Bool("key.boolean", true), - attribute.Float64("key.float", 42.4), - attribute.String("key.string", "string"), - ) - logger.Warnf(ctx, "I have params: %v and attributes", "example param") + // Or inline using WithCtx() + newCtx := context.Background() + // WithCtx() does not modify the original context attached on the logger. + logger.Info().WithCtx(newCtx).Emit("context passed") + + // You can use the logger like [fmt.Print] + logger.Info().Emit("Hello ", "world!") + // Or like [fmt.Printf] + logger.Info().Emitf("Hello %v!", "world") } ``` -Currently the `attribute` API supports only these value types: `int`, `string`, `bool`, and `float`. +You can also pass additional permanent attributes to the logger via `SetAttributes`, or attach certain attributes to the `LogEntry` itself. +These attributes do not persist after Emitting the `LogEntry`. All attributes will be searchable in the Logs UI. + +```go +logger.SetAttributes( + attribute.Int("key.int", 42), + attribute.Bool("key.boolean", true), + attribute.Float64("key.float", 42.4), + attribute.String("key.string", "string"), +) +logger.Warn().Emitf("I have params: %v and attributes", "example param") + +// This entry would contain all attributes attached to the logger. +// However, it's also possible to overwrite them. +logger.Info().String("key.string", "newstring").Emit("overwriting key.string") +``` + +Currently, the `attribute` API supports only these value types: `int`, `string`, `bool`, and `float`. ## Integrations +### Supported libraries +- [Slog](/platforms/go/guides/slog) +- [Logrus](/platforms/go/guides/logrus) + ### `io.Writer` interface -The `sentry.Logger` implements the `io.Writer` interface, so you can easily inject the logger into your existing setup. +The `sentry.Logger` implements the `io.Writer` interface, so you can easily inject the logger into your existing setup. However, to correctly +link your traces you would need to create a new logger everytime you want to pass a new context. Due to this limitation we recommend using the +`sentry.Logger` or any of the other supported integrations. ```go sentryLogger := sentry.NewLogger(ctx) logger := log.New(sentryLogger, "", log.LstdFlags) logger.Println("Implementing log.Logger") - -slogger := slog.New(slog.NewJSONHandler(sentryLogger, nil)) -slogger.Info("Implementing slog.Logger") ``` - - In order to properly attach the correct trace with each Log entry, a - `context.Context` is required. The `Write` function of the `io.Writer` - interface doesn't provide `context`, so wrapping the custom logger will not - get the trace and current span attached. We recommend using the - `sentry.Logger` to ensure your logs are connected to spans and errors in the - Sentry UI. - - -### Integrations -- [Slog](/platforms/go/guides/slog) -- [Logrus](/platforms/go/guides/logrus) - -### Upcoming Integrations - -We're actively working on adding more integration support for Logs. Currently, we are looking at adding support for [`zerolog`](https://pkg.go.dev/github.com/rs/zerolog). You can follow this [GitHub issue](https://github.com/getsentry/sentry-go/issues/1015) to track progress. - ## Options ### BeforeSendLog @@ -135,25 +113,26 @@ We're actively working on adding more integration support for Logs. Currently, w To filter logs, or update them before they are sent to Sentry, you can use the `BeforeSendLog` client option. ```go -if err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - EnableLogs: true, - BeforeSendLog: func(log *Log) *Log { - // filter out all trace logs - if log.Level == sentry.LogLevelTrace { - return nil - } - - // filter all logs below warning - if log.Severity <= LogSeverityInfo { - return nil - } - }, -}); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", err) -} +sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + EnableLogs: true, + BeforeSendLog: func(log *sentry.Log) *sentry.Log { + // filter out all trace logs + if log.Level == sentry.LogLevelTrace { + return nil + } + + // filter all logs below warning + if log.Severity <= sentry.LogSeverityInfo { + return nil + } + return log + }, +}) ``` ### Debug If the `Debug` init option is set to true, calls to the `sentry.Logger` will also print to the console with the appropriate log level. + + diff --git a/docs/platforms/go/guides/logrus/index.mdx b/docs/platforms/go/guides/logrus/index.mdx index 3a339e3daa62c..edb62a669989e 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -11,30 +11,34 @@ Go API documentation for the [`sentrylogrus` package](https://pkg.go.dev/github. Logrus structured logging is supported in Sentry Go SDK version `0.34.0` and above. -## Install +## Setup +Install the `sentrylogrus` package: ```bash go get github.com/getsentry/sentry-go/logrus ``` - +To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. - +```go +sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + // Enable logs to be sent to Sentry + EnableLogs: true, +}) +``` + +## Configure + +`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 + +## Usage 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" -) - func main() { // Initialize Logrus logger := logrus.New() @@ -111,29 +115,47 @@ func main() { } ``` -## Configure - -`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 - ### 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: "https://examplePublicKey@o0.ingest.sentry.io/0", + EnableLogs: true, +}); err != nil { + log.Fatalf("Sentry initialization failed: %v", err) +} +hub := sentry.CurrentHub() +logHook := sentrylogrus.NewLogHookFromClient( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + hub.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,7 +163,24 @@ 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() +eventHook := sentrylogrus.NewEventHookFromClient( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + hub.Client(), +) ``` @@ -172,6 +211,8 @@ sentryHandler := sentryhttp.New(sentryhttp.Options{}) http.Handle("/async", sentryHandler.Handle(http.HandlerFunc(myAsyncHandler))) ``` + + ## Logs For comprehensive logging setup with Logrus, including advanced configuration options and best practices, see the [Go Logs documentation](/platforms/go/logs/). The Logrus integration shown above provides seamless integration with Sentry's structured logging features. diff --git a/docs/platforms/go/guides/slog/index.mdx b/docs/platforms/go/guides/slog/index.mdx index 56a82ef287221..88e0a3ea0b224 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -11,51 +11,86 @@ Go API documentation for the [`sentryslog` package](https://pkg.go.dev/github.co Slog structured logging is supported in Sentry Go SDK version `0.34.0` and above. -## Install +## Setup +Install the `sentryslog` package: ```bash go get github.com/getsentry/sentry-go/slog ``` - +To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. - +```go +sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + // Enable logs to be sent to Sentry + EnableLogs: true, +}) +``` -To integrate Sentry with slog, you need to set up a Sentry handler and configure the Sentry client. +## 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 -import ( - "context" - "fmt" - "log" - "time" +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 +} +``` - "log/slog" +## Usage - "github.com/getsentry/sentry-go" - sentryslog "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 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, + if err := sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", EnableLogs: true, - }) - if err != nil { - log.Fatal(err) + }); err != nil { + log.Fatalf("Sentry initialization failed: %v", 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) - // Configure `slog` to use Sentry as a handler ctx := context.Background() + // Configure the sentryslog handler. + // The handler lets you explicitly declare how to handle each log level. + // You can handle logs as events or as log entries by specifying the `EventLevel` and `LogLevel` slices. 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 + EventLevel: []slog.Level{slog.LevelError}, // Only LevelError entries will be sent as events + LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Only LevelWarn and LevelInfo entries will be sent as logs }.NewSentryHandler(ctx) logger := slog.New(handler) logger = logger.With("release", "v1.0.0") @@ -74,117 +109,7 @@ func main() { } ``` -## 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 - -### 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`. - -### Example: Sending Logs as Events - -```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") -``` - -### Example: Sending Logs as Logs - -```go -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))) -} -``` - -Note: Ensure Sentry is flushed before the application exits to avoid losing any pending events. + ## Logs diff --git a/includes/logs/go-ctx-usage-alert.mdx b/includes/logs/go-ctx-usage-alert.mdx new file mode 100644 index 0000000000000..bbb527739e15e --- /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 From 2f11d7493c613200ceebb7e3a9edcaa094589093 Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Mon, 7 Jul 2025 15:06:12 +0200 Subject: [PATCH 2/8] feat(go): refactor initial guide pages --- docs/platforms/go/common/index.mdx | 14 -- docs/platforms/go/guides/echo/index.mdx | 99 +++++-------- docs/platforms/go/guides/fasthttp/index.mdx | 96 +++++------- docs/platforms/go/guides/fiber/index.mdx | 120 ++++++--------- docs/platforms/go/guides/gin/index.mdx | 95 +++++------- docs/platforms/go/guides/http/index.mdx | 83 ++++++----- docs/platforms/go/guides/iris/index.mdx | 95 +++++------- docs/platforms/go/guides/logrus/index.mdx | 137 ++++++++++-------- docs/platforms/go/guides/negroni/index.mdx | 101 ++++++------- docs/platforms/go/guides/slog/index.mdx | 101 ++++++++----- docs/platforms/go/guides/zerolog/index.mdx | 89 ++++++++---- .../getting-started-config/go.mdx | 63 ++++---- 12 files changed, 511 insertions(+), 582 deletions(-) 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/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..2bce153bdbb0c 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..8ffef8bf7ce2b 100644 --- a/docs/platforms/go/guides/http/index.mdx +++ b/docs/platforms/go/guides/http/index.mdx @@ -28,41 +28,57 @@ 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 +// 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 +``` + + ```go -import ( - "fmt" - "net/http" +// Create an instance of sentryhttp +sentryHandler := sentryhttp.New(sentryhttp.Options{ + Repanic: true, + WaitForDelivery: false, + Timeout: 5 * time.Second, +}) +``` - "github.com/getsentry/sentry-go" - sentryhttp "github.com/getsentry/sentry-go/http" -) +## Verify -// 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 +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 +88,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..9a508f9c72b7e 100644 --- a/docs/platforms/go/guides/iris/index.mdx +++ b/docs/platforms/go/guides/iris/index.mdx @@ -7,75 +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/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. @@ -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..ed8a00b11522a 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -14,12 +14,86 @@ 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 + +#### LogHook + +Use `sentrylogrus.NewLogHook()` to send structured logs to Sentry. This hook captures log entries and sends them to Sentry's structured logging system. + +```go +logHook, err := sentrylogrus.NewLogHook( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + EnableLogs: true, // Required for log entries + }) +``` + +#### EventHook + +Use `sentrylogrus.NewEventHook()` to send log entries as Sentry events. This is useful for error tracking and alerting. + +```go +eventHook, err := sentrylogrus.NewEventHook( + []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}, + sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + Debug: true, + AttachStacktrace: true, + }) +``` + + + 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. + + +## Verify + +```go +// Initialize Logrus +logger := logrus.New() +logger.Level = logrus.DebugLevel +logger.Out = os.Stderr + +// Create event hook for errors +eventHook, err := sentrylogrus.NewEventHook([]logrus.Level{ + logrus.ErrorLevel, + logrus.FatalLevel, + logrus.PanicLevel, +}, sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + AttachStacktrace: true, +}) +if err != nil { + panic(err) +} +defer eventHook.Flush(5 * time.Second) +logger.AddHook(eventHook) + +// Test logging - this will be sent to Sentry as an event +logger.Error("This error will be sent to Sentry!") + +// Example of logging with attributes +logger.WithField("user", "test-user").Error("An error occurred") +``` + +## Usage 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. @@ -111,67 +185,6 @@ func main() { } ``` -## Configure - -`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 - -### LogHook - -Use `sentrylogrus.NewLogHook()` to send structured logs to Sentry. This hook captures log entries and sends them to Sentry's structured logging system. - -```go -logHook, err := sentrylogrus.NewLogHook( - []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, - sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - EnableLogs: true, // Required for log entries - }) -``` - -### EventHook - -Use `sentrylogrus.NewEventHook()` to send log entries as Sentry events. This is useful for error tracking and alerting. - -```go -eventHook, err := sentrylogrus.NewEventHook( - []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}, - sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - Debug: true, - AttachStacktrace: true, - }) -``` - - - 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 For comprehensive logging setup with Logrus, including advanced configuration options and best practices, see the [Go Logs documentation](/platforms/go/logs/). The Logrus integration shown above provides seamless integration with Sentry's structured logging features. 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..a9d33854e5fef 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -14,12 +14,73 @@ 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 ``` - +## Configure + +### Initialize the Sentry SDK + + + +### Slog Integration + +`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 +``` + +## Verify + +```go +// 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) + +// Test logging - this will be sent to Sentry as an event +logger.Error("This error will be sent to Sentry!") + +// Example of logging with attributes +logger.With("user", "test-user").Error("An error occurred") +``` + +## Usage + +### 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`. To integrate Sentry with slog, you need to set up a Sentry handler and configure the Sentry client. @@ -74,44 +135,6 @@ func main() { } ``` -## 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 - -### 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`. - ### Example: Sending Logs as Events ```go 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/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) ``` From 90740d9832a30c5f4ad115ab20967b8018a103d8 Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Mon, 7 Jul 2025 15:12:05 +0200 Subject: [PATCH 3/8] fix dsn --- docs/platforms/go/common/integrations/index.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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{} }, From 6ee5de735f0e62c06777aa75e2065f0283660661 Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Mon, 7 Jul 2025 15:20:26 +0200 Subject: [PATCH 4/8] misc fixes --- .../go/common/configuration/options.mdx | 11 ++-------- .../go/common/configuration/transports.mdx | 22 +++++-------------- docs/platforms/go/guides/fiber/index.mdx | 2 +- docs/platforms/go/guides/http/index.mdx | 14 +----------- docs/platforms/go/guides/iris/index.mdx | 2 +- docs/platforms/go/guides/slog/index.mdx | 2 +- .../configuration/drain-example/go.mdx | 22 ++++++++----------- 7 files changed, 21 insertions(+), 54 deletions(-) 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/guides/fiber/index.mdx b/docs/platforms/go/guides/fiber/index.mdx index 2bce153bdbb0c..3a3128125ad7c 100644 --- a/docs/platforms/go/guides/fiber/index.mdx +++ b/docs/platforms/go/guides/fiber/index.mdx @@ -3,7 +3,7 @@ title: Fiber description: "Learn how to add Sentry instrumentation to programs using the Fiber package." --- -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 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. [Go Dev-style API documentation](https://godoc.org/github.com/getsentry/sentry-go/fiber) is also available. diff --git a/docs/platforms/go/guides/http/index.mdx b/docs/platforms/go/guides/http/index.mdx index 8ffef8bf7ce2b..bf03bbb552308 100644 --- a/docs/platforms/go/guides/http/index.mdx +++ b/docs/platforms/go/guides/http/index.mdx @@ -7,22 +7,10 @@ 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 ``` diff --git a/docs/platforms/go/guides/iris/index.mdx b/docs/platforms/go/guides/iris/index.mdx index 9a508f9c72b7e..473b819039f39 100644 --- a/docs/platforms/go/guides/iris/index.mdx +++ b/docs/platforms/go/guides/iris/index.mdx @@ -28,7 +28,7 @@ go get github.com/getsentry/sentry-go/iris ```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, diff --git a/docs/platforms/go/guides/slog/index.mdx b/docs/platforms/go/guides/slog/index.mdx index a9d33854e5fef..e1d0a5c120fad 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -26,7 +26,7 @@ go get github.com/getsentry/sentry-go/slog -### Slog Integration +### Options `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: 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) ``` From 7f3550a386d3e7db73b52be2e6d5d075d8da2758 Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Tue, 8 Jul 2025 11:38:41 +0200 Subject: [PATCH 5/8] refactor segments for consistency --- docs/platforms/go/common/logs/index.mdx | 54 +++++++++++------------ docs/platforms/go/guides/logrus/index.mdx | 12 ++--- docs/platforms/go/guides/slog/index.mdx | 2 +- includes/logs/go-ctx-usage-alert.mdx | 2 +- 4 files changed, 36 insertions(+), 34 deletions(-) diff --git a/docs/platforms/go/common/logs/index.mdx b/docs/platforms/go/common/logs/index.mdx index e37d7573ca579..9d0b154e28680 100644 --- a/docs/platforms/go/common/logs/index.mdx +++ b/docs/platforms/go/common/logs/index.mdx @@ -11,9 +11,9 @@ With Sentry Structured Logs, you can send text based log information from your a ## Requirements -Logs in Go are supported in Sentry Go SDK version `0.33.0` and above. For using integrations of other log libraries, have a look at each specific page for more details on requirements. +Logs in Go are supported in Sentry Go SDK version `0.33.0` and above. To use integrations with other logging libraries, check their specific documentation pages for detailed requirements. -## Setup +## Configure To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. @@ -25,6 +25,31 @@ sentry.Init(sentry.ClientOptions{ }) ``` +### Options + +#### BeforeSendLog + +To filter logs, or update them before they are sent to Sentry, you can use the `BeforeSendLog` client option. + +```go +sentry.Init(sentry.ClientOptions{ + Dsn: "___PUBLIC_DSN___", + EnableLogs: true, + BeforeSendLog: func(log *sentry.Log) *sentry.Log { + // filter out all trace logs + if log.Level == sentry.LogLevelTrace { + return nil + } + + // filter all logs below warning + if log.Severity <= sentry.LogSeverityInfo { + return nil + } + return log + }, +}) +``` + ## Usage Once the feature is enabled on the SDK and the SDK is initialized, you can send logs by using the `sentry.Logger` API or our different integrations. @@ -106,31 +131,6 @@ logger := log.New(sentryLogger, "", log.LstdFlags) logger.Println("Implementing log.Logger") ``` -## Options - -### BeforeSendLog - -To filter logs, or update them before they are sent to Sentry, you can use the `BeforeSendLog` client option. - -```go -sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - EnableLogs: true, - BeforeSendLog: func(log *sentry.Log) *sentry.Log { - // filter out all trace logs - if log.Level == sentry.LogLevelTrace { - return nil - } - - // filter all logs below warning - if log.Severity <= sentry.LogSeverityInfo { - return nil - } - return log - }, -}) -``` - ### Debug If the `Debug` init option is set to true, calls to the `sentry.Logger` will also print to the console with the appropriate log level. diff --git a/docs/platforms/go/guides/logrus/index.mdx b/docs/platforms/go/guides/logrus/index.mdx index edb62a669989e..476c3b2327e59 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -11,13 +11,15 @@ Go API documentation for the [`sentrylogrus` package](https://pkg.go.dev/github. Logrus structured logging is supported in Sentry Go SDK version `0.34.0` and above. -## Setup +## Install Install the `sentrylogrus` package: ```bash go get github.com/getsentry/sentry-go/logrus ``` +## Configure + To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. ```go @@ -28,7 +30,7 @@ sentry.Init(sentry.ClientOptions{ }) ``` -## Configure +### 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 @@ -117,7 +119,7 @@ func main() { ### LogHook -You have two ways to create a new `LogHook`. Either by using `sentrylogrus.NewLogHook()` and passing the `sentry.ClientOptions` or +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. @@ -151,7 +153,7 @@ logHook := sentrylogrus.NewLogHookFromClient( ### EventHook -You also have two ways to create a new `EventHook`. Either by using `sentrylogrus.NewEventHook()` and passing the `sentry.ClientOptions` or +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. @@ -187,7 +189,7 @@ eventHook := sentrylogrus.NewEventHookFromClient( 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 +## 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. diff --git a/docs/platforms/go/guides/slog/index.mdx b/docs/platforms/go/guides/slog/index.mdx index 88e0a3ea0b224..d215b125e9244 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -70,7 +70,7 @@ type Option struct { ## Usage -To integrate Sentry with slog, you need to set up a Sentry handler and configure the Sentry client. +To integrate Sentry with slog, you need to set up a Sentry handler and configure the Sentry client: ```go func main() { diff --git a/includes/logs/go-ctx-usage-alert.mdx b/includes/logs/go-ctx-usage-alert.mdx index bbb527739e15e..effe5480ded43 100644 --- a/includes/logs/go-ctx-usage-alert.mdx +++ b/includes/logs/go-ctx-usage-alert.mdx @@ -1,4 +1,4 @@ -## Correlating Logs with Traces +## 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 From 57a499e4b87229a6480913adc65297e528548ffd Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Tue, 8 Jul 2025 11:39:07 +0200 Subject: [PATCH 6/8] remove unneeded segment on logrus --- docs/platforms/go/guides/logrus/index.mdx | 24 ----------------------- 1 file changed, 24 deletions(-) diff --git a/docs/platforms/go/guides/logrus/index.mdx b/docs/platforms/go/guides/logrus/index.mdx index 476c3b2327e59..3b5b42d900e2d 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -189,30 +189,6 @@ eventHook := sentrylogrus.NewEventHookFromClient( 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 From 0cb3f2444d187cc03f9e4f3a8a6f269bd5eaa45f Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Tue, 8 Jul 2025 12:18:16 +0200 Subject: [PATCH 7/8] follow base structure on logs --- docs/platforms/go/guides/logrus/index.mdx | 172 ++++++++++------------ docs/platforms/go/guides/slog/index.mdx | 70 +++------ 2 files changed, 102 insertions(+), 140 deletions(-) diff --git a/docs/platforms/go/guides/logrus/index.mdx b/docs/platforms/go/guides/logrus/index.mdx index 3b5b42d900e2d..73f4f83e0e043 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -13,22 +13,16 @@ Logrus structured logging is supported in Sentry Go SDK version `0.34.0` and abo ## Install -Install the `sentrylogrus` package: ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/logrus ``` ## Configure -To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. +### Initialize the Sentry SDK -```go -sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // Enable logs to be sent to Sentry - EnableLogs: true, -}) -``` + ### Options @@ -36,85 +30,69 @@ sentry.Init(sentry.ClientOptions{ - **Levels**: A slice of `logrus.Level` specifying which log levels to capture - **ClientOptions**: Standard `sentry.ClientOptions` for configuration -## Usage +## 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 -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") +// 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 + +// Get the Sentry client from the current hub +hub := sentry.CurrentHub() +client := hub.Client() +if client == nil { + log.Fatalf("Sentry client is nil") } + +// Create log hook to send logs on Info level +logHook := sentrylogrus.NewLogHookFromClient( + []logrus.Level{logrus.InfoLevel}, + client, +) + +// 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 @@ -139,16 +117,21 @@ logHook, err := sentrylogrus.NewLogHook( Use `NewLogHookFromClient` if you've already initialized the Sentry SDK. ```go if err := sentry.Init(sentry.ClientOptions{ - Dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", + Dsn: "___PUBLIC_DSN___", EnableLogs: true, }); err != nil { log.Fatalf("Sentry initialization failed: %v", err) } hub := sentry.CurrentHub() -logHook := sentrylogrus.NewLogHookFromClient( - []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, - hub.Client(), -) +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 @@ -179,10 +162,15 @@ if err := sentry.Init(sentry.ClientOptions{ log.Fatalf("Sentry initialization failed: %v", err) } hub := sentry.CurrentHub() -eventHook := sentrylogrus.NewEventHookFromClient( - []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, - hub.Client(), -) +client := hub.Client() +if client != nil { + eventHook := sentrylogrus.NewEventHookFromClient( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + client, + ) +} else { + log.Fatalf("Sentrylogrus initialization failed: nil client") +} ``` diff --git a/docs/platforms/go/guides/slog/index.mdx b/docs/platforms/go/guides/slog/index.mdx index d215b125e9244..0a230280d2a13 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -11,24 +11,20 @@ Go API documentation for the [`sentryslog` package](https://pkg.go.dev/github.co Slog structured logging is supported in Sentry Go SDK version `0.34.0` and above. -## Setup +## Install -Install the `sentryslog` package: ```bash +go get github.com/getsentry/sentry-go go get github.com/getsentry/sentry-go/slog ``` -To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. +## Configure -```go -sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // Enable logs to be sent to Sentry - EnableLogs: true, -}) -``` +### Initialize the Sentry SDK -## Configure + + +### Options `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: @@ -68,45 +64,23 @@ type Option struct { } ``` -## Usage - -To integrate Sentry with slog, you need to set up a Sentry handler and configure the Sentry client: +## Verify ```go -func main() { - if err := sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - EnableLogs: true, - }); err != nil { - log.Fatalf("Sentry initialization failed: %v", 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) - - ctx := context.Background() - // Configure the sentryslog handler. - // The handler lets you explicitly declare how to handle each log level. - // You can handle logs as events or as log entries by specifying the `EventLevel` and `LogLevel` slices. - handler := sentryslog.Option{ - EventLevel: []slog.Level{slog.LevelError}, // Only LevelError entries will be sent as events - LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Only LevelWarn and LevelInfo entries 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 `slog` to use Sentry as a handler +ctx := context.Background() +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") ``` From d19bcfa9271829b8f1199118ce5ca4601e0b63cc Mon Sep 17 00:00:00 2001 From: Giannis Gkiortzis Date: Tue, 8 Jul 2025 13:49:44 +0200 Subject: [PATCH 8/8] create platform includes snippet for logs config --- docs/platforms/go/common/logs/index.mdx | 10 ++---- docs/platforms/go/guides/logrus/index.mdx | 2 +- docs/platforms/go/guides/slog/index.mdx | 2 +- .../go.mdx | 31 +++++++++++++++++++ 4 files changed, 36 insertions(+), 9 deletions(-) create mode 100644 platform-includes/getting-started-include-logs-config/go.mdx diff --git a/docs/platforms/go/common/logs/index.mdx b/docs/platforms/go/common/logs/index.mdx index 9d0b154e28680..8a2196196fdce 100644 --- a/docs/platforms/go/common/logs/index.mdx +++ b/docs/platforms/go/common/logs/index.mdx @@ -15,15 +15,11 @@ Logs in Go are supported in Sentry Go SDK version `0.33.0` and above. To use int ## Configure +### Initialize the Sentry SDK + To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true. -```go -sentry.Init(sentry.ClientOptions{ - Dsn: "___PUBLIC_DSN___", - // Enable logs to be sent to Sentry - EnableLogs: true, -}) -``` + ### Options diff --git a/docs/platforms/go/guides/logrus/index.mdx b/docs/platforms/go/guides/logrus/index.mdx index 73f4f83e0e043..b05fcec5dcba4 100644 --- a/docs/platforms/go/guides/logrus/index.mdx +++ b/docs/platforms/go/guides/logrus/index.mdx @@ -22,7 +22,7 @@ go get github.com/getsentry/sentry-go/logrus ### Initialize the Sentry SDK - + ### Options diff --git a/docs/platforms/go/guides/slog/index.mdx b/docs/platforms/go/guides/slog/index.mdx index 0a230280d2a13..fc8edfa8cafdc 100644 --- a/docs/platforms/go/guides/slog/index.mdx +++ b/docs/platforms/go/guides/slog/index.mdx @@ -22,7 +22,7 @@ go get github.com/getsentry/sentry-go/slog ### Initialize the Sentry SDK - + ### Options 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) +```