Skip to content

Commit

Permalink
Add mutex to event
Browse files Browse the repository at this point in the history
  • Loading branch information
lukazakrajsek-soniox committed Sep 27, 2024
1 parent 0d7d7cf commit ddf9800
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion event.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package events
import (
"fmt"
"log/slog"
"sync"

"github.com/google/uuid"
"golang.org/x/xerrors"
Expand All @@ -26,6 +27,7 @@ var (

type Event struct {
attrs map[string]slog.Value
mutex sync.RWMutex

baseLogger *slog.Logger
}
Expand All @@ -44,11 +46,17 @@ func NewEvent(logger *slog.Logger) *Event {
}

func (e *Event) SetAttr(key string, value any) {
e.mutex.Lock()
e.attrs[key] = slog.AnyValue(value)
e.mutex.Unlock()
}

func (e *Event) GetAttr(key string) any {
return e.attrs[key].Any()
e.mutex.RLock()
value := e.attrs[key].Any()
e.mutex.RUnlock()

return value
}

func (e *Event) SetError(err error) {
Expand All @@ -64,6 +72,8 @@ func (e *Event) SetError(err error) {
}

func (e *Event) Logger() *slog.Logger {
e.mutex.RLock()

attrs := make([]any, 0, len(e.attrs))

for key, value := range e.attrs {
Expand All @@ -73,5 +83,7 @@ func (e *Event) Logger() *slog.Logger {
})
}

e.mutex.RUnlock()

return e.baseLogger.With(attrs...)
}

0 comments on commit ddf9800

Please sign in to comment.