Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/platforms/go/common/enriching-events/scopes/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ made will stay isolated within the <PlatformIdentifier name="with-scope" /> call
more easily isolate pieces of context information to specific locations in your code or
even call <PlatformIdentifier name="clear" /> to briefly remove all context information.

### Using <PlatformIdentifier name="push-scope" />

<PlatformIdentifier name="push-scope" /> and <PlatformIdentifier name="configure-scope" /> both modify the active scope, but they differ in how long the change lasts:

- <PlatformIdentifier name="configure-scope" /> updates the current scope and keeps the change until you unset it or clear the scope.
- <PlatformIdentifier name="push-scope" /> adds a child scope. Call <PlatformIdentifier name="pop-scope" /> to restore the previous scope, usually with `defer`.
- <PlatformIdentifier name="with-scope" /> clones the current scope for a callback and restores it automatically when the callback returns.

In Go, <PlatformIdentifier name="push-scope" /> returns the new scope so you can configure it directly:

```go
scope := sentry.PushScope()
defer sentry.PopScope()
scope.SetTag("request.type", "background")
```

## Setting Attributes

You can set typed attributes on the scope using `SetAttributes`. These attributes are attached to logs and metrics emitted within the scope. Attributes use the `attribute` package for type safety.
Expand Down
77 changes: 14 additions & 63 deletions docs/platforms/go/common/logs/logrus.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Logrus
description: "Integrate Logrus with Sentry to capture and send both logs and events."
description: "Integrate Logrus with Sentry to capture structured logs."
sidebar_order: 10
---

Expand Down Expand Up @@ -28,12 +28,13 @@ go get github.com/getsentry/sentry-go/logrus
### Options

`sentrylogrus` provides two types of hooks to configure the integration with Sentry. Both hooks accept these options:

- **Levels**: A slice of `logrus.Level` specifying which log levels to capture
- **ClientOptions**: Standard `sentry.ClientOptions` for configuration

## Verify

To integrate Sentry with Logrus, you can set up both log hooks and event hooks to capture different types of data at various log levels.
To integrate Sentry with Logrus, configure the log hook with the levels you want to send as structured logs.

```go
// Initialize Sentry SDK
Expand All @@ -54,44 +55,29 @@ if client == nil {
log.Fatalf("Sentry client is nil")
}

// Create log hook to send logs on Info level
// Send selected log levels as structured logs.
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,
},
[]logrus.Level{logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel},
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)
// Flush before calling os.Exit(1) when using logger.Fatal.
logrus.RegisterExitHandler(func() {
eventHook.Flush(5 * time.Second)
logHook.Flush(5 * time.Second)
})

// Info level is sent as a log to Sentry
// Sending an info level log to Sentry.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: adding a hyphen makes it a bit clearer that "info" is referring to the log level

Suggested change
// Sending an info level log to Sentry.
// Sending an info-level 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
// Sending an error level log to Sentry.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l:

Suggested change
// Sending an error level log to Sentry.
// Sending an error-level log to Sentry.

logger.Errorf("oh no!")

// Fatal level is sent as an error event to Sentry and terminates the application
// Fatal also sends an error level log to Sentry, while also terminating the current process.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: you're missing a newline

Suggested change
// Fatal also sends an error level log to Sentry, while also terminating the current process.
// Fatal also sends an error level log to Sentry, while also terminating the current process.

logger.Fatalf("can't continue...")
Comment on lines 79 to 81

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: Would add comments before each of these lines to stay consistent with other lines here and to make it clear to users what they should expect

```

Expand All @@ -102,6 +88,7 @@ by using `sentrylogrus.NewLogHookFromClient()` and passing an already created `s
send them to Sentry's structured logging system.

#### NewLogHook

```go
logHook, err := sentrylogrus.NewLogHook(
[]logrus.Level{logrus.InfoLevel, logrus.WarnLevel},
Expand All @@ -114,6 +101,7 @@ logHook, err := sentrylogrus.NewLogHook(
#### NewLogHookFromClient

Use `NewLogHookFromClient` if you've already initialized the Sentry SDK.

```go
if err := sentry.Init(sentry.ClientOptions{
Dsn: "___PUBLIC_DSN___",
Expand All @@ -132,46 +120,9 @@ if client != nil {
}
```

### EventHook

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},
sentry.ClientOptions{
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",
}); err != nil {
log.Fatalf("Sentry initialization failed: %v", err)
}
hub := sentry.CurrentHub()
client := hub.Client()
if client != nil {
eventHook := sentrylogrus.NewEventHookFromClient(
[]logrus.Level{logrus.InfoLevel, logrus.WarnLevel},
client,
)
} else {
log.Fatalf("Sentrylogrus initialization failed: nil client")
}
```
Comment on lines -135 to -171

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[question] are these no longer supported, or simply discouraged?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no longer supported


<Alert>
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.
Logrus sends records as structured logs. To capture an error as an issue, call
`sentry.CaptureException` or `sentry.CaptureMessage` explicitly.
</Alert>

<Include name="logs/go-ctx-usage-alert.mdx"/>
<Include name="logs/go-ctx-usage-alert.mdx" />
20 changes: 8 additions & 12 deletions docs/platforms/go/common/logs/slog.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,16 @@ go get github.com/getsentry/sentry-go/slog

`sentryslog` accepts a `sentryslog.Option` struct to control which records are sent to Sentry and how they're enriched before sending.

| Field | Type | Description | Default |
| ----------------- | ------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `EventLevel` | `[]slog.Level` | Log levels to capture as Sentry events | `[]slog.Level{slog.LevelError, sentryslog.LevelFatal}` |
| `LogLevel` | `[]slog.Level` | Log levels to capture as Sentry log entries | `[]slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal}` |
| `Hub` | `*sentry.Hub` | Hub to use when capturing events | Current hub |
| `Converter` | `Converter` | Custom converter for turning log records into Sentry events | `sentryslog.DefaultConverter` |
| `AttrFromContext` | `[]func(context.Context) []slog.Attr` | Functions that add attributes from the current context | None |
| `AddSource` | `bool` | Include file and line information in Sentry output | `false` |
| `ReplaceAttr` | `func([]string, slog.Attr) slog.Attr` | Rewrite or filter attributes before sending | None |
| Field | Type | Description | Default |
| ----------------- | ------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `LogLevel` | `[]slog.Level` | Log levels to capture as Sentry log entries | `[]slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal}` |
| `AttrFromContext` | `[]func(context.Context) []slog.Attr` | Add attributes from the current context | None |
| `AddSource` | `bool` | Include source information in Sentry output | `false` |
| `ReplaceAttr` | `func([]string, slog.Attr) slog.Attr` | Rewrite or filter attributes before sending | None |

## Verify

This example sends `ERROR` records as events and `INFO`/`WARN` records as structured logs.
This example sends selected records as structured logs.

```go
package main
Expand All @@ -56,8 +53,7 @@ import (
func main() {
ctx := context.Background()
handler := sentryslog.Option{
EventLevel: []slog.Level{slog.LevelError, sentryslog.LevelFatal},
LogLevel: []slog.Level{slog.LevelInfo, slog.LevelWarn},
LogLevel: []slog.Level{slog.LevelInfo, slog.LevelWarn, slog.LevelError},
AddSource: true,
}.NewSentryHandler(ctx)

Expand Down
10 changes: 6 additions & 4 deletions docs/platforms/go/common/migration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ go get github.com/getsentry/sentry-go

raven-go


```go
import "github.com/getsentry/raven-go"

Expand Down Expand Up @@ -71,7 +70,6 @@ SetIncludePaths()

sentry-go


```go
sentry.Init(sentry.ClientOptions{
Dsn: "___PUBLIC_DSN___",
Expand All @@ -91,7 +89,6 @@ Available options: see [Configuration](/platforms/go/configuration/options/) sec

By default, TLS uses the host's root CA set. If you don't have `ca-certificates` (which should be your go-to way of fixing the missing certificates issue) and want to use `gocertifi` instead, you can provide pre-loaded cert files as one of the options to `sentry.Init` call:


```go
package main

Expand Down Expand Up @@ -362,11 +359,16 @@ sentry-go

```go
// use `sentry.WithScope`, see "Context / Per-event Section"
import "github.com/getsentry/sentry-go/attribute"

path := "filename.ext"
f, err := os.Open(path)
if err != nil {
sentry.WithScope(func(scope *sentry.Scope) {
scope.SetExtras(map[string]interface{}{"path": path, "cwd": os.Getwd()})
scope.SetAttributes(
attribute.String("path", path),
attribute.String("cwd", os.Getwd()),
)
sentry.CaptureException(err)
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ Sentry provides middleware for the following Go HTTP frameworks:
| --------- | -------------------- | ------------------------------------------------ |
| Gin | `sentry-go/gin` | [Gin guide](/platforms/go/guides/gin/) |
| Echo | `sentry-go/echo` | [Echo guide](/platforms/go/guides/echo/) |
| Fiber | `sentry-go/fiber` | [Fiber guide](/platforms/go/guides/fiber/) |
| Fiber v2 | `sentry-go/fiber` | [Fiber guide](/platforms/go/guides/fiber/) |
| Fiber v3 | `sentry-go/fiberv3` | [Fiber v3 guide](/platforms/go/guides/fiberv3/) |
| net/http | `sentry-go/http` | [net/http guide](/platforms/go/guides/http/) |
| Iris | `sentry-go/iris` | [Iris guide](/platforms/go/guides/iris/) |
| FastHTTP | `sentry-go/fasthttp` | [FastHTTP guide](/platforms/go/guides/fasthttp/) |
Expand Down
2 changes: 1 addition & 1 deletion docs/platforms/go/guides/echo/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ app.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
app.GET("/", func(ctx *echo.Context) error {
if hub := sentryecho.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
scope.SetAttributes(attribute.String("unwantedQuery", "someQueryDataMaybe"))
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
})
}
Expand Down
3 changes: 1 addition & 2 deletions docs/platforms/go/guides/fasthttp/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{
defaultHandler := func(ctx *fasthttp.RequestCtx) {
if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
scope.SetAttributes(attribute.String("unwantedQuery", "someQueryDataMaybe"))
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
})
}
Expand Down Expand Up @@ -131,7 +131,6 @@ if err := fasthttp.ListenAndServe(":3000", sentryHandler.Handle(fastHTTPHandler)

### Accessing Context in `BeforeSend` callback


```go
sentry.Init(sentry.ClientOptions{
Dsn: "___PUBLIC_DSN___",
Expand Down
2 changes: 1 addition & 1 deletion docs/platforms/go/guides/fiber/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ sentryHandler := sentryfiber.New(sentryfiber.Options{
defaultHandler := func(ctx *fiber.Ctx) error {
if hub := sentryfiber.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
scope.SetAttributes(attribute.String("unwantedQuery", "someQueryDataMaybe"))
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
})
}
Expand Down
Loading
Loading