Skip to content

Error log events are not attached to the correct trace #1129

@Gitznik

Description

@Gitznik

How do you use Sentry?

Sentry SaaS (sentry.io)

SDK version

0.36.2

Go version

1.25.2

Are you using Go Modules?

yes

Steps to reproduce

package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"time"

	"github.com/getsentry/sentry-go"
	sentrygin "github.com/getsentry/sentry-go/gin"
	sentryslog "github.com/getsentry/sentry-go/slog"
	"github.com/gin-gonic/gin"
)

func main() {
	if err := sentry.Init(sentry.ClientOptions{
		Dsn:              "YOUR_DSN",
		EnableTracing:    true,
		TracesSampleRate: 1.0,
		EnableLogs:       true,
		Environment:      "testing",
		SendDefaultPII:   true,
	}); err != nil {
		slog.Error("Sentry initialization failed", "error", err)
		os.Exit(1)
	}
	defer sentry.Flush(5 * time.Second)

	router := gin.Default()
	router.Use(sentrygin.New(sentrygin.Options{Repanic: true}))

	router.GET("/send-logs", func(c *gin.Context) {
		logger := NewSentryLogger(c.Request.Context())
		logger.Info("I'm on the http trace")
		logger.Error("This should be on the http trace, but is on the runner trace")
		if hub := sentrygin.GetHubFromContext(c); hub != nil {
			hub.CaptureException(fmt.Errorf("this is actually on the trace"))
		}
		c.Status(http.StatusOK)
	})

	runnerCtx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go Runner(runnerCtx)

	if err := router.Run(); err != nil {
		os.Exit(1)
	}
}

func Runner(ctx context.Context) {
	for {
		span := sentry.StartTransaction(ctx, "pubsub.dispatch_messages_run")
		defer span.Finish()
		runCtx := span.Context()
		logger := NewSentryLogger(runCtx)
		logger.Info("I'm on the runner trace")
		logger.Error("I'm also on the runner trace")
		select {
		case <-time.After(10 * time.Second):
		case <-runCtx.Done():
			return
		}
	}
}

func NewSentryLogger(ctx context.Context) *slog.Logger {
	handler := sentryslog.Option{
		EventLevel: []slog.Level{slog.LevelError},
		LogLevel:   []slog.Level{slog.LevelWarn, slog.LevelInfo},
		AddSource:  true,
	}.NewSentryHandler(ctx)
	return slog.New(handler)
}

Expected result

When using sentryslog and sentrygin, configuring slog to send events for log level Error and attaching the slog handler to the request context, it should attach the issue to the http call, even if there may be other transactions running at the same time.

Actual result

The issues are all attached to the transaction of the Runner goroutine, while the logs are correctly attached to their corresponding context (http call/Runner)

Metadata

Metadata

Assignees

Labels

No fields configured for issues without a type.

Projects

Status

No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions