Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace SentryWrapperLogger by slog-sentry #673

Merged
merged 1 commit into from
Sep 7, 2024
Merged
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
2 changes: 1 addition & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -510,10 +510,10 @@ func Load(configFlag string, version string) *Config {
}

if config.Sentry.Dsn != "" {
slog.Info("enabling sentry integration")
if config.Sentry.Environment == "" {
config.Sentry.Environment = config.Env
}
slog.Info("enabling sentry integration", "environment", config.Sentry.Environment)
initSentry(config.Sentry, config.IsDev())
}

Expand Down
120 changes: 24 additions & 96 deletions config/sentry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,121 +2,50 @@ package config

import (
"github.com/getsentry/sentry-go"
"io"
slogsentry "github.com/samber/slog-sentry/v2"
"log/slog"
"net/http"
"os"
"strings"
"time"
)

// How to: Logging
// Use slog.[Debug|Info|Warn|Error|Fatal]() by default
// Use config.Log().[Debug|Info|Warn|Error|Fatal]() when wanting the log to appear in Sentry as well

var sentryWrapperLogger *SentryWrapperLogger

type capturingWriter struct {
Writer io.Writer
Message string
}

func (c *capturingWriter) Clear() {
c.Message = ""
}

func (c *capturingWriter) Write(p []byte) (n int, err error) {
c.Message = string(p)
return c.Writer.Write(p)
// SentryLogger wraps slog.Logger and provides a Fatal method
type SentryLogger struct {
*slog.Logger
}

// SentryWrapperLogger is a wrapper around a slog.Logger that forwards events to Sentry in addition and optionally allows to attach a request context
type SentryWrapperLogger struct {
Logger *slog.Logger
req *http.Request
outWriter *capturingWriter
errWriter *capturingWriter
}
var sentryLogger *SentryLogger

func Log() *SentryWrapperLogger {
if sentryWrapperLogger != nil {
return sentryWrapperLogger
func Log() *SentryLogger {
if sentryLogger != nil {
return sentryLogger
}

ow, ew := &capturingWriter{Writer: os.Stdout}, &capturingWriter{Writer: os.Stderr}
var handler slog.Handler
level := slog.LevelInfo
if Get().IsDev() {
handler = slog.NewTextHandler(io.MultiWriter(ow, ew), &slog.HandlerOptions{
Level: slog.LevelDebug,
})
} else {
handler = slog.NewJSONHandler(io.MultiWriter(ow, ew), &slog.HandlerOptions{
Level: slog.LevelInfo,
})
}

// Create a custom handler that writes to both output and error writers
sentryWrapperLogger = &SentryWrapperLogger{
Logger: slog.New(handler),
outWriter: ow,
errWriter: ew,
level = slog.LevelDebug
}
return sentryWrapperLogger
}

func (l *SentryWrapperLogger) Request(req *http.Request) *SentryWrapperLogger {
l.req = req
return l
}

func (l *SentryWrapperLogger) Debug(msg string, params ...interface{}) {
l.outWriter.Clear()
l.Logger.Debug(msg, params...)
l.log(l.errWriter.Message, sentry.LevelDebug)
}

func (l *SentryWrapperLogger) Info(msg string, params ...interface{}) {
l.outWriter.Clear()
l.Logger.Info(msg, params...)
l.log(l.errWriter.Message, sentry.LevelInfo)
}
handler := slogsentry.Option{Level: level}.NewSentryHandler()
logger := slog.New(handler)

func (l *SentryWrapperLogger) Warn(msg string, params ...interface{}) {
l.outWriter.Clear()
l.Logger.Warn(msg, params...)
l.log(l.errWriter.Message, sentry.LevelWarning)
}
sentryLogger = &SentryLogger{Logger: logger}

func (l *SentryWrapperLogger) Error(msg string, params ...interface{}) {
l.errWriter.Clear()
l.Logger.Error(msg, params...)
l.log(l.errWriter.Message, sentry.LevelError)
return sentryLogger
}

func (l *SentryWrapperLogger) Fatal(msg string, params ...interface{}) {
l.errWriter.Clear()
l.Logger.Error(msg, params...)
l.log(l.errWriter.Message, sentry.LevelFatal)
func (l *SentryLogger) Fatal(msg string, args ...any) {
l.Error(msg, args...)
sentry.Flush(2 * time.Second)
os.Exit(1)
}

func (l *SentryWrapperLogger) log(msg string, level sentry.Level) {
event := sentry.NewEvent()
event.Level = level
event.Message = msg

if l.req != nil {
if h := l.req.Context().Value(sentry.HubContextKey); h != nil {
hub := h.(*sentry.Hub)
hub.Scope().SetRequest(l.req)
if uid := getPrincipal(l.req); uid != "" {
hub.Scope().SetUser(sentry.User{ID: uid})
}
hub.CaptureEvent(event)
return
}
}

sentry.CaptureEvent(event)
func (l *SentryLogger) Request(r *http.Request) *slog.Logger {
return l.Logger.With(slog.Any("http_request", r))
}

var excludedRoutes = []string{
Expand Down Expand Up @@ -146,11 +75,10 @@ func initSentry(config sentryConfig, debug bool) {
return float64(config.SampleRate)
},
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 {
if uid := getPrincipal(req); uid != "" {
event.User.ID = uid
}
r, ok := event.Contexts["extra"]["http_request"]
if ok {
if uid := getPrincipal(r.(*http.Request)); uid != "" {
event.User.ID = uid
}
}
return event
Expand Down
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ require (
gorm.io/gorm v1.25.11
)

require (
github.com/samber/lo v1.44.0 // indirect
github.com/samber/slog-common v0.17.0 // indirect
)

require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/BurntSushi/toml v1.4.0 // indirect
Expand Down Expand Up @@ -74,6 +79,7 @@ require (
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/samber/slog-sentry/v2 v2.8.0
github.com/stretchr/objx v0.5.2 // indirect
github.com/swaggo/files v1.0.1 // indirect
golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,12 @@ github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/samber/lo v1.44.0 h1:5il56KxRE+GHsm1IR+sZ/6J42NODigFiqCWpSc2dybA=
github.com/samber/lo v1.44.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU=
github.com/samber/slog-common v0.17.0 h1:HdRnk7QQTa9ByHlLPK3llCBo8ZSX3F/ZyeqVI5dfMtI=
github.com/samber/slog-common v0.17.0/go.mod h1:mZSJhinB4aqHziR0SKPqpVZjJ0JO35JfH+dDIWqaCBk=
github.com/samber/slog-sentry/v2 v2.8.0 h1:XDsokN3fW/vT/LyekgyP6AxWct7YvDwbjrMBSxwVW7Y=
github.com/samber/slog-sentry/v2 v2.8.0/go.mod h1:OkeRGrUxkcLqGyePoL8x6lkQkP/N4pWuXOjq3wsRm/k=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
Expand Down
14 changes: 7 additions & 7 deletions routes/api/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,29 +141,29 @@ func (h *MetricsHandler) getUserMetrics(user *models.User) (*mm.Metrics, error)

summaryAllTime, err := h.summarySrvc.Aliased(time.Time{}, time.Now(), user, h.summarySrvc.Retrieve, nil, false)
if err != nil {
conf.Log().Error("failed to retrieve all time summary for user '%s' for metric", user.ID)
conf.Log().Error("failed to retrieve all time summary for metric", "userID", user.ID, "error", err)
return nil, err
}

from, to := helpers.MustResolveIntervalRawTZ("today", user.TZ())

summaryToday, err := h.summarySrvc.Aliased(from, to, user, h.summarySrvc.Retrieve, nil, false)
if err != nil {
conf.Log().Error("failed to retrieve today's summary for user '%s' for metric", user.ID)
conf.Log().Error("failed to retrieve today's summary for metric", "userID", user.ID, "error", err)
return nil, err
}

heartbeatCount, err := h.heartbeatSrvc.CountByUser(user)
if err != nil {
conf.Log().Error("failed to count heartbeats for user '%s' for metric", user.ID)
conf.Log().Error("failed to count heartbeats for metric", "userID", user.ID, "error", err)
return nil, err
}

var leaderboard models.Leaderboard
if h.config.App.LeaderboardEnabled {
leaderboard, err = h.leaderboardSrvc.GetByIntervalAndUser(h.leaderboardSrvc.GetDefaultScope(), user.ID, false)
if err != nil {
conf.Log().Error("failed to fetch leaderboard for user '%s' for metric", user.ID)
conf.Log().Error("failed to fetch leaderboard for metric", "userID", user.ID, "error", err)
return nil, err
}
}
Expand Down Expand Up @@ -402,7 +402,7 @@ func (h *MetricsHandler) getAdminMetrics(user *models.User) (*mm.Metrics, error)

activeUsers, err := h.userSrvc.GetActive(false)
if err != nil {
conf.Log().Error("failed to retrieve active users for metric - %v", err)
conf.Log().Error("failed to retrieve active users for metric", "error", err)
return nil, err
}
slog.Debug("finished getting active users", "duration", time.Since(t0))
Expand Down Expand Up @@ -439,7 +439,7 @@ func (h *MetricsHandler) getAdminMetrics(user *models.User) (*mm.Metrics, error)

userCounts, err := h.heartbeatSrvc.CountByUsers(activeUsers)
if err != nil {
conf.Log().Error("failed to count heartbeats for active users", err.Error())
conf.Log().Error("failed to count heartbeats for active users", "error", err.Error())
return nil, err
}

Expand All @@ -465,7 +465,7 @@ func (h *MetricsHandler) getAdminMetrics(user *models.User) (*mm.Metrics, error)
wp.Submit(func() {
summary, err := h.summarySrvc.Aliased(from, to, activeUsers[i], h.summarySrvc.Retrieve, nil, false) // only using aliased because aliased has caching
if err != nil {
conf.Log().Error("failed to get total time for user '%s' as part of metrics, %v", activeUsers[i].ID, err)
conf.Log().Error("failed to get total time for user as part of metrics", "userID", activeUsers[i].ID, "error", err)
return
}
lock.Lock()
Expand Down
2 changes: 1 addition & 1 deletion routes/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ func (h *LoginHandler) PostSignup(w http.ResponseWriter, r *http.Request) {
}

if err := h.keyValueSrvc.DeleteString(inviteCodeKey); err != nil {
conf.Log().Error("failed to revoke %s", inviteCodeKey)
conf.Log().Error("failed to revoke invite code", "inviteCodeKey", inviteCodeKey, "error", err)
}
}

Expand Down
6 changes: 3 additions & 3 deletions routes/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ func (h *SettingsHandler) actionImportWakatime(w http.ResponseWriter, r *http.Re
stream, importError = importer.Import(user, latest.Time.T(), time.Now())
}
if importError != nil {
conf.Log().Error("wakatime import for user '%s' failed - %v", user.ID, importError)
conf.Log().Error("wakatime import for user failed", "userID", user.ID, "error", importError)
return
}

Expand Down Expand Up @@ -808,12 +808,12 @@ func (h *SettingsHandler) validateWakatimeKey(apiKey string, baseUrl string) boo
func (h *SettingsHandler) regenerateSummaries(user *models.User) error {
slog.Info("clearing summaries for user", "userID", user.ID)
if err := h.summarySrvc.DeleteByUser(user.ID); err != nil {
conf.Log().Error("failed to clear summaries: %v", err)
conf.Log().Error("failed to clear summaries", "error", err)
return err
}

if err := h.aggregationSrvc.AggregateSummaries(datastructure.New(user.ID)); err != nil {
conf.Log().Error("failed to regenerate summaries: %v", err)
conf.Log().Error("failed to regenerate summaries", "error", err)
return err
}

Expand Down
2 changes: 1 addition & 1 deletion routes/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func NewSubscriptionHandler(
if err := handler.cancelUserSubscription(user); err == nil {
slog.Info("successfully cancelled subscription for user", "userID", user.ID, "email", user.Email, "stripeCustomerID", user.StripeCustomerId)
} else {
conf.Log().Error("failed to cancel subscription for user '%s' (email '%s', stripe customer '%s') - %v", user.ID, user.Email, user.StripeCustomerId, err)
conf.Log().Error("failed to cancel subscription for user", "userID", user.ID, "email", user.Email, "stripeCustomerID", user.StripeCustomerId, "error", err)
}
}
}(&onUserDelete)
Expand Down