-
Notifications
You must be signed in to change notification settings - Fork 215
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
Add Slog integration #865
+1,567
−4
Merged
Add Slog integration #865
Changes from all commits
Commits
Show all changes
40 commits
Select commit
Hold shift + click to select a range
77a05ad
add slog integration
ribice 58768fb
add slog integration
ribice 3a08154
remove comment
ribice d700b0c
revert empty line in go.sum
ribice 680336f
add build constraint
ribice 57b14cc
Merge branch 'master' into slog
ribice 381fbb4
add tests
ribice b271b84
add tests
ribice 0fb55f9
replace if with switch
ribice 8fa0b0c
linter fixes
ribice f03152a
simplify attrToSentryEvent
ribice cbe5d36
more tests
ribice 98f0e9f
improve tests
ribice 3b12de9
improve tests
ribice 826105f
linter fixes
ribice a6079d0
more tests
ribice bded79e
more tests
ribice 7da0be8
linter fix
ribice 8a95b37
add example
ribice 098d9ec
update changelog
ribice e3ba7bd
improve comments
ribice d286b10
Merge branch 'master' into slog
ribice 5acfc1b
Merge branch 'master' into slog
ribice 19b9c2f
fix changelog conflict
ribice 6539084
fix pr number
ribice fef2742
Merge branch 'master' into slog
ribice 7165698
merge master
ribice 4def70e
make slog integration a module
ribice 43b7672
make slog integration a module
ribice 7ce566c
Update CHANGELOG.md
ribice b9bee10
update go mod
ribice 5f5b2c6
Merge branch 'slog' of https://github.com/getsentry/sentry-go into slog
ribice 420dac1
fix makefile
ribice edf6484
update go version
ribice e473e0b
update go mod
ribice 8aaac00
update go.mod go version for slog
ribice 97662ee
remove echo
ribice 1b5c88a
update go vet script in makefile
ribice 8fd1a24
merge master
ribice 08340ae
fix failing tests
ribice File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"time" | ||
|
||
"log/slog" | ||
|
||
"github.com/getsentry/sentry-go" | ||
sentryslog "github.com/getsentry/sentry-go/slog" | ||
) | ||
|
||
func main() { | ||
err := sentry.Init(sentry.ClientOptions{ | ||
Dsn: "https://4d0ead95fb645aaab4fc95d21aaa6de1@o447951.ingest.us.sentry.io/4506954545758208", | ||
EnableTracing: false, | ||
}) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
defer sentry.Flush(2 * time.Second) | ||
|
||
logger := slog.New(sentryslog.Option{Level: slog.LevelDebug}.NewSentryHandler()) | ||
logger = logger.With("release", "v1.0.0") | ||
|
||
logger. | ||
With( | ||
slog.Group("user", | ||
slog.String("id", "user-123"), | ||
slog.Time("created_at", time.Now()), | ||
), | ||
). | ||
With("environment", "dev"). | ||
With("error", fmt.Errorf("an error")). | ||
Error("a message") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,260 @@ | ||
package sentryslog | ||
|
||
import ( | ||
"context" | ||
"encoding" | ||
"fmt" | ||
"log/slog" | ||
"runtime" | ||
"strconv" | ||
) | ||
|
||
func source(sourceKey string, r *slog.Record) slog.Attr { | ||
fs := runtime.CallersFrames([]uintptr{r.PC}) | ||
f, _ := fs.Next() | ||
var args []any | ||
if f.Function != "" { | ||
args = append(args, slog.String("function", f.Function)) | ||
} | ||
if f.File != "" { | ||
args = append(args, slog.String("file", f.File)) | ||
} | ||
if f.Line != 0 { | ||
args = append(args, slog.Int("line", f.Line)) | ||
} | ||
|
||
return slog.Group(sourceKey, args...) | ||
} | ||
|
||
type replaceAttrFn = func(groups []string, a slog.Attr) slog.Attr | ||
|
||
func replaceAttrs(fn replaceAttrFn, groups []string, attrs ...slog.Attr) []slog.Attr { | ||
for i := range attrs { | ||
attr := attrs[i] | ||
value := attr.Value.Resolve() | ||
if value.Kind() == slog.KindGroup { | ||
attrs[i].Value = slog.GroupValue(replaceAttrs(fn, append(groups, attr.Key), value.Group()...)...) | ||
} else if fn != nil { | ||
attrs[i] = fn(groups, attr) | ||
} | ||
} | ||
|
||
return attrs | ||
} | ||
|
||
func attrsToMap(attrs ...slog.Attr) map[string]any { | ||
output := make(map[string]any, len(attrs)) | ||
|
||
attrsByKey := groupValuesByKey(attrs) | ||
for k, values := range attrsByKey { | ||
v := mergeAttrValues(values...) | ||
if v.Kind() == slog.KindGroup { | ||
output[k] = attrsToMap(v.Group()...) | ||
} else { | ||
output[k] = v.Any() | ||
} | ||
} | ||
|
||
return output | ||
} | ||
|
||
func extractError(attrs []slog.Attr) ([]slog.Attr, error) { | ||
for i := range attrs { | ||
attr := attrs[i] | ||
|
||
if _, ok := errorKeys[attr.Key]; !ok { | ||
continue | ||
} | ||
|
||
if err, ok := attr.Value.Resolve().Any().(error); ok { | ||
return append(attrs[:i], attrs[i+1:]...), err | ||
} | ||
} | ||
|
||
return attrs, nil | ||
} | ||
|
||
func mergeAttrValues(values ...slog.Value) slog.Value { | ||
v := values[0] | ||
|
||
for i := 1; i < len(values); i++ { | ||
if v.Kind() != slog.KindGroup || values[i].Kind() != slog.KindGroup { | ||
v = values[i] | ||
continue | ||
} | ||
|
||
v = slog.GroupValue(append(v.Group(), values[i].Group()...)...) | ||
} | ||
|
||
return v | ||
} | ||
|
||
func groupValuesByKey(attrs []slog.Attr) map[string][]slog.Value { | ||
result := map[string][]slog.Value{} | ||
|
||
for _, item := range attrs { | ||
key := item.Key | ||
result[key] = append(result[key], item.Value) | ||
} | ||
|
||
return result | ||
} | ||
|
||
func attrsToString(attrs ...slog.Attr) map[string]string { | ||
output := make(map[string]string, len(attrs)) | ||
|
||
for _, attr := range attrs { | ||
k, v := attr.Key, attr.Value | ||
output[k] = valueToString(v) | ||
} | ||
|
||
return output | ||
} | ||
|
||
func valueToString(v slog.Value) string { | ||
switch v.Kind() { | ||
case slog.KindAny, slog.KindLogValuer, slog.KindGroup: | ||
return anyValueToString(v) | ||
case slog.KindInt64: | ||
return fmt.Sprintf("%d", v.Int64()) | ||
case slog.KindUint64: | ||
return fmt.Sprintf("%d", v.Uint64()) | ||
case slog.KindFloat64: | ||
return fmt.Sprintf("%f", v.Float64()) | ||
case slog.KindString: | ||
return v.String() | ||
case slog.KindBool: | ||
return strconv.FormatBool(v.Bool()) | ||
case slog.KindDuration: | ||
return v.Duration().String() | ||
case slog.KindTime: | ||
return v.Time().UTC().String() | ||
} | ||
return anyValueToString(v) | ||
} | ||
|
||
func anyValueToString(v slog.Value) string { | ||
tm, ok := v.Any().(encoding.TextMarshaler) | ||
if !ok { | ||
return fmt.Sprintf("%+v", v.Any()) | ||
} | ||
|
||
data, err := tm.MarshalText() | ||
if err != nil { | ||
return fmt.Sprintf("%+v", v.Any()) | ||
} | ||
|
||
return string(data) | ||
} | ||
|
||
func appendRecordAttrsToAttrs(attrs []slog.Attr, groups []string, record *slog.Record) []slog.Attr { | ||
output := make([]slog.Attr, len(attrs)) | ||
copy(output, attrs) | ||
|
||
for i, j := 0, len(groups)-1; i < j; i, j = i+1, j-1 { | ||
groups[i], groups[j] = groups[j], groups[i] | ||
} | ||
record.Attrs(func(attr slog.Attr) bool { | ||
for i := range groups { | ||
attr = slog.Group(groups[i], attr) | ||
} | ||
output = append(output, attr) | ||
return true | ||
}) | ||
|
||
return output | ||
} | ||
|
||
func removeEmptyAttrs(attrs []slog.Attr) []slog.Attr { | ||
result := []slog.Attr{} | ||
|
||
for _, attr := range attrs { | ||
if attr.Key == "" { | ||
continue | ||
} | ||
|
||
if attr.Value.Kind() == slog.KindGroup { | ||
values := removeEmptyAttrs(attr.Value.Group()) | ||
if len(values) == 0 { | ||
continue | ||
} | ||
attr.Value = slog.GroupValue(values...) | ||
result = append(result, attr) | ||
} else if !attr.Value.Equal(slog.Value{}) { | ||
result = append(result, attr) | ||
} | ||
} | ||
|
||
return result | ||
} | ||
|
||
func contextExtractor(ctx context.Context, fns []func(ctx context.Context) []slog.Attr) []slog.Attr { | ||
attrs := []slog.Attr{} | ||
for _, fn := range fns { | ||
attrs = append(attrs, fn(ctx)...) | ||
} | ||
return attrs | ||
} | ||
|
||
func appendAttrsToGroup(groups []string, actualAttrs []slog.Attr, newAttrs ...slog.Attr) []slog.Attr { | ||
actualAttrsCopy := make([]slog.Attr, len(actualAttrs)) | ||
copy(actualAttrsCopy, actualAttrs) | ||
|
||
if len(groups) == 0 { | ||
return uniqAttrs(append(actualAttrsCopy, newAttrs...)) | ||
} | ||
|
||
groupKey := groups[0] | ||
for i := range actualAttrsCopy { | ||
attr := actualAttrsCopy[i] | ||
if attr.Key == groupKey && attr.Value.Kind() == slog.KindGroup { | ||
actualAttrsCopy[i] = slog.Group(groupKey, toAnySlice(appendAttrsToGroup(groups[1:], attr.Value.Group(), newAttrs...))...) | ||
return actualAttrsCopy | ||
} | ||
} | ||
|
||
return uniqAttrs( | ||
append( | ||
actualAttrsCopy, | ||
slog.Group( | ||
groupKey, | ||
toAnySlice(appendAttrsToGroup(groups[1:], []slog.Attr{}, newAttrs...))..., | ||
), | ||
), | ||
) | ||
} | ||
|
||
func toAnySlice(collection []slog.Attr) []any { | ||
result := make([]any, len(collection)) | ||
for i := range collection { | ||
result[i] = collection[i] | ||
} | ||
return result | ||
} | ||
|
||
func uniqAttrs(attrs []slog.Attr) []slog.Attr { | ||
return uniqByLast(attrs, func(item slog.Attr) string { | ||
return item.Key | ||
}) | ||
} | ||
|
||
func uniqByLast[T any, U comparable](collection []T, iteratee func(item T) U) []T { | ||
result := make([]T, 0, len(collection)) | ||
seen := make(map[U]int, len(collection)) | ||
seenIndex := 0 | ||
|
||
for _, item := range collection { | ||
key := iteratee(item) | ||
|
||
if index, ok := seen[key]; ok { | ||
result[index] = item | ||
continue | ||
} | ||
|
||
seen[key] = seenIndex | ||
seenIndex++ | ||
result = append(result, item) | ||
} | ||
|
||
return result | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm just wondering: why not use https://pkg.go.dev/log/slog#Value.String ?