Skip to content

Commit 32293f6

Browse files
committed
change API on Go Logs page
1 parent 381c26e commit 32293f6

File tree

3 files changed

+111
-101
lines changed

3 files changed

+111
-101
lines changed

docs/platforms/go/common/logs/index.mdx

Lines changed: 76 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -11,149 +11,124 @@ With Sentry Structured Logs, you can send text based log information from your a
1111

1212
## Requirements
1313

14-
Logs in Go are supported in Sentry Go SDK version `0.33.0` and above.
14+
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.
1515

16-
## Setup
16+
## Configure
17+
18+
### Initialize the Sentry SDK
1719

1820
To enable logging, you need to initialize the SDK with the `EnableLogs` option set to true.
1921

20-
```go
21-
package main
22+
<PlatformContent includePath="getting-started-include-logs-config" />
2223

23-
import (
24-
"context"
25-
"github.com/getsentry/sentry-go"
26-
"time"
27-
)
24+
### Options
2825

29-
func main() {
30-
if err := sentry.Init(sentry.ClientOptions{
26+
#### BeforeSendLog
27+
28+
To filter logs, or update them before they are sent to Sentry, you can use the `BeforeSendLog` client option.
29+
30+
```go
31+
sentry.Init(sentry.ClientOptions{
3132
Dsn: "___PUBLIC_DSN___",
3233
EnableLogs: true,
33-
}); err != nil {
34-
fmt.Printf("Sentry initialization failed: %v\n", err)
35-
}
36-
// Flush buffered events before the program terminates.
37-
// Set the timeout to the maximum duration the program can afford to wait.
38-
defer sentry.Flush(2 * time.Second)
39-
}
34+
BeforeSendLog: func(log *sentry.Log) *sentry.Log {
35+
// filter out all trace logs
36+
if log.Level == sentry.LogLevelTrace {
37+
return nil
38+
}
39+
40+
// filter all logs below warning
41+
if log.Severity <= sentry.LogSeverityInfo {
42+
return nil
43+
}
44+
return log
45+
},
46+
})
4047
```
4148

4249
## Usage
4350

44-
Once the feature is enabled on the SDK and the SDK is initialized, you can send logs by using
45-
the `sentry.Logger` API.
51+
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.
4652

47-
The `Sentry.Logger` API exposes methods that support six different log levels: `trace`,
48-
`debug`, `info`, `warn`, `error` and `fatal`. The methods support both `fmt.Print` and `fmt.Printf` like syntax.
49-
If you pass in format specifiers like `%v`, these will be sent to Sentry, and can be searched from within the Logs UI,
50-
and even added to the Logs views as a dedicated column.
53+
The `sentry.Logger` API exposes methods that support six different log levels:
54+
- `trace`
55+
- `debug`
56+
- `info`
57+
- `warn`
58+
- `error`
59+
- `fatal`
5160

52-
```go
53-
ctx := context.Background()
54-
logger := sentry.NewLogger(ctx)
55-
56-
// You can use the logger like [fmt.Print]
57-
logger.Info(ctx, "Hello ", "world!")
58-
// Or like [fmt.Printf]
59-
logger.Infof(ctx, "Hello %v!", "world")
60-
```
61-
62-
You can also pass additional attributes to the logger via the `SetAttributes` function. These attributes will also be searchable in the Logs UI.
61+
The methods support both `fmt.Print` and `fmt.Printf` like syntax. If you pass in format specifiers like `%v`, these will be
62+
sent to Sentry, and can be searched from within the Logs UI, and even added to the Logs views as a dedicated column.
6363

6464
```go
65-
package main
66-
67-
import (
68-
"context"
69-
"github.com/getsentry/sentry-go"
70-
"github.com/getsentry/sentry-go/attribute"
71-
"time"
72-
)
73-
7465
func main() {
75-
err := sentry.Init(sentry.ClientOptions{
66+
if err := sentry.Init(sentry.ClientOptions{
7667
Dsn: "___PUBLIC_DSN___",
7768
EnableLogs: true,
78-
})
79-
if err != nil {
80-
panic(err)
69+
}); err != nil {
70+
log.Fatalf("Sentry initialization failed: %v", err)
8171
}
72+
// Flush buffered events before the program terminates.
73+
// Set the timeout to the maximum duration the program can afford to wait.
8274
defer sentry.Flush(2 * time.Second)
8375

76+
// The SentryLogger requires context, to link logs with the appropriate traces. You can either create a new logger
77+
// by providing the context, or use WithCtx() to pass the context inline.
8478
ctx := context.Background()
8579
logger := sentry.NewLogger(ctx)
8680

87-
logger.SetAttributes(
88-
attribute.Int("key.int", 42),
89-
attribute.Bool("key.boolean", true),
90-
attribute.Float64("key.float", 42.4),
91-
attribute.String("key.string", "string"),
92-
)
93-
logger.Warnf(ctx, "I have params: %v and attributes", "example param")
81+
// Or inline using WithCtx()
82+
newCtx := context.Background()
83+
// WithCtx() does not modify the original context attached on the logger.
84+
logger.Info().WithCtx(newCtx).Emit("context passed")
85+
86+
// You can use the logger like [fmt.Print]
87+
logger.Info().Emit("Hello ", "world!")
88+
// Or like [fmt.Printf]
89+
logger.Info().Emitf("Hello %v!", "world")
9490
}
9591
```
9692

97-
Currently the `attribute` API supports only these value types: `int`, `string`, `bool`, and `float`.
98-
99-
## Integrations
100-
101-
### `io.Writer` interface
102-
103-
The `sentry.Logger` implements the `io.Writer` interface, so you can easily inject the logger into your existing setup.
93+
You can also pass additional permanent attributes to the logger via `SetAttributes`, or attach certain attributes to the `LogEntry` itself.
94+
These attributes do not persist after Emitting the `LogEntry`. All attributes will be searchable in the Logs UI.
10495

10596
```go
106-
sentryLogger := sentry.NewLogger(ctx)
107-
logger := log.New(sentryLogger, "", log.LstdFlags)
108-
logger.Println("Implementing log.Logger")
97+
logger.SetAttributes(
98+
attribute.Int("key.int", 42),
99+
attribute.Bool("key.boolean", true),
100+
attribute.Float64("key.float", 42.4),
101+
attribute.String("key.string", "string"),
102+
)
103+
logger.Warn().Emitf("I have params: %v and attributes", "example param")
109104

110-
slogger := slog.New(slog.NewJSONHandler(sentryLogger, nil))
111-
slogger.Info("Implementing slog.Logger")
105+
// This entry would contain all attributes attached to the logger.
106+
// However, it's also possible to overwrite them.
107+
logger.Info().String("key.string", "newstring").Emit("overwriting key.string")
112108
```
113109

114-
<Alert>
115-
In order to properly attach the correct trace with each Log entry, a
116-
`context.Context` is required. The `Write` function of the `io.Writer`
117-
interface doesn't provide `context`, so wrapping the custom logger will not
118-
get the trace and current span attached. We recommend using the
119-
`sentry.Logger` to ensure your logs are connected to spans and errors in the
120-
Sentry UI.
121-
</Alert>
110+
Currently, the `attribute` API supports only these value types: `int`, `string`, `bool`, and `float`.
111+
112+
## Integrations
122113

123-
### Integrations
114+
### Supported libraries
124115
- [Slog](/platforms/go/guides/slog)
125116
- [Logrus](/platforms/go/guides/logrus)
126117

127-
### Upcoming Integrations
128-
129-
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.
130-
131-
## Options
132-
133-
### BeforeSendLog
118+
### `io.Writer` interface
134119

135-
To filter logs, or update them before they are sent to Sentry, you can use the `BeforeSendLog` client option.
120+
The `sentry.Logger` implements the `io.Writer` interface, so you can easily inject the logger into your existing setup. However, to correctly
121+
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
122+
`sentry.Logger` or any of the other supported integrations.
136123

137124
```go
138-
if err := sentry.Init(sentry.ClientOptions{
139-
Dsn: "___PUBLIC_DSN___",
140-
EnableLogs: true,
141-
BeforeSendLog: func(log *Log) *Log {
142-
// filter out all trace logs
143-
if log.Level == sentry.LogLevelTrace {
144-
return nil
145-
}
146-
147-
// filter all logs below warning
148-
if log.Severity <= LogSeverityInfo {
149-
return nil
150-
}
151-
},
152-
}); err != nil {
153-
fmt.Printf("Sentry initialization failed: %v\n", err)
154-
}
125+
sentryLogger := sentry.NewLogger(ctx)
126+
logger := log.New(sentryLogger, "", log.LstdFlags)
127+
logger.Println("Implementing log.Logger")
155128
```
156129

157130
### Debug
158131

159132
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.
133+
134+
<Include name="logs/go-ctx-usage-alert.mdx"/>

includes/logs/go-ctx-usage-alert.mdx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
## Correlating Logs With Traces
2+
3+
In order to properly attach the correct trace with each log entry, a `context.Context` is required.
4+
If you're using logs combined with tracing, you should pass the correct context to properly attach each trace with the appropriate logs.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<OnboardingOptionButtons
2+
options={[
3+
'error-monitoring',
4+
'performance',
5+
]}
6+
/>
7+
8+
```go
9+
err := sentry.Init(sentry.ClientOptions{
10+
Dsn: "___PUBLIC_DSN___",
11+
// Enable printing of SDK debug messages.
12+
// Useful when getting started or trying to figure something out.
13+
Debug: true,
14+
// Adds request headers and IP for users,
15+
// visit: https://docs.sentry.io/platforms/go/data-management/data-collected/ for more info
16+
SendDefaultPII: true,
17+
EnableLogs: true,
18+
// ___PRODUCT_OPTION_START___ performance
19+
EnableTracing: true,
20+
// Set TracesSampleRate to 1.0 to capture 100%
21+
// of transactions for tracing.
22+
TracesSampleRate: 1.0,
23+
// ___PRODUCT_OPTION_END___ performance
24+
})
25+
if err != nil {
26+
log.Fatalf("sentry.Init: %s", err)
27+
}
28+
// Flush buffered events before the program terminates.
29+
// Set the timeout to the maximum duration the program can afford to wait.
30+
defer sentry.Flush(2 * time.Second)
31+
```

0 commit comments

Comments
 (0)