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

Add Slog integration #865

Merged
merged 40 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
77a05ad
add slog integration
ribice Jul 28, 2024
58768fb
add slog integration
ribice Jul 28, 2024
3a08154
remove comment
ribice Jul 28, 2024
d700b0c
revert empty line in go.sum
ribice Jul 28, 2024
680336f
add build constraint
ribice Jul 30, 2024
57b14cc
Merge branch 'master' into slog
ribice Jul 30, 2024
381fbb4
add tests
ribice Jul 30, 2024
b271b84
add tests
ribice Jul 30, 2024
0fb55f9
replace if with switch
ribice Jul 30, 2024
8fa0b0c
linter fixes
ribice Jul 30, 2024
f03152a
simplify attrToSentryEvent
ribice Jul 30, 2024
cbe5d36
more tests
ribice Jul 30, 2024
98f0e9f
improve tests
ribice Jul 30, 2024
3b12de9
improve tests
ribice Jul 30, 2024
826105f
linter fixes
ribice Jul 30, 2024
a6079d0
more tests
ribice Jul 31, 2024
bded79e
more tests
ribice Jul 31, 2024
7da0be8
linter fix
ribice Jul 31, 2024
8a95b37
add example
ribice Jul 31, 2024
098d9ec
update changelog
ribice Jul 31, 2024
e3ba7bd
improve comments
ribice Aug 4, 2024
d286b10
Merge branch 'master' into slog
ribice Aug 15, 2024
5acfc1b
Merge branch 'master' into slog
ribice Aug 30, 2024
19b9c2f
fix changelog conflict
ribice Oct 15, 2024
6539084
fix pr number
ribice Oct 15, 2024
fef2742
Merge branch 'master' into slog
ribice Oct 29, 2024
7165698
merge master
ribice Nov 5, 2024
4def70e
make slog integration a module
ribice Nov 5, 2024
43b7672
make slog integration a module
ribice Nov 5, 2024
7ce566c
Update CHANGELOG.md
ribice Nov 5, 2024
b9bee10
update go mod
ribice Nov 5, 2024
5f5b2c6
Merge branch 'slog' of https://github.com/getsentry/sentry-go into slog
ribice Nov 5, 2024
420dac1
fix makefile
ribice Nov 5, 2024
edf6484
update go version
ribice Nov 5, 2024
e473e0b
update go mod
ribice Nov 5, 2024
8aaac00
update go.mod go version for slog
ribice Nov 5, 2024
97662ee
remove echo
ribice Nov 5, 2024
1b5c88a
update go vet script in makefile
ribice Nov 7, 2024
8fd1a24
merge master
ribice Nov 8, 2024
08340ae
fix failing tests
ribice Nov 8, 2024
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
3 changes: 3 additions & 0 deletions .craft.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ targets:
- name: github
tagPrefix: otel/v
tagOnly: true
- name: github
tagPrefix: slog/v
tagOnly: true
- name: registry
sdks:
github:getsentry/sentry-go:
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

### Features

- Add `sentryslog` integration ([#865](https://github.com/getsentry/sentry-go/pull/865))

- Always set Mechanism Type to generic ([#896](https://github.com/getsentry/sentry-go/pull/897))

### Misc
Expand Down
7 changes: 3 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,21 @@ test-coverage: $(COVERAGE_REPORT_DIR) clean-report-dir ## Test with coverage en
mod-tidy: ## Check go.mod tidiness
set -e ; \
for dir in $(ALL_GO_MOD_DIRS); do \
cd "$${dir}"; \
echo ">>> Running 'go mod tidy' for module: $${dir}"; \
go mod tidy -go=1.21 -compat=1.21; \
(cd "$${dir}" && go mod tidy -go=1.21 -compat=1.21); \
done; \
git diff --exit-code;
.PHONY: mod-tidy

vet: ## Run "go vet"
set -e ; \
for dir in $(ALL_GO_MOD_DIRS); do \
cd "$${dir}"; \
echo ">>> Running 'go vet' for module: $${dir}"; \
go vet ./...; \
(cd "$${dir}" && go vet ./...); \
done;
.PHONY: vet


lint: ## Lint (using "golangci-lint")
golangci-lint run
.PHONY: lint
Expand Down
38 changes: 38 additions & 0 deletions _examples/slog/main.go
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")
}
260 changes: 260 additions & 0 deletions slog/common.go
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

Check warning on line 83 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L82-L83

Added lines #L82 - L83 were not covered by tests
}

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 {
Copy link

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 ?

switch v.Kind() {
case slog.KindAny, slog.KindLogValuer, slog.KindGroup:
return anyValueToString(v)

Check warning on line 117 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L116-L117

Added lines #L116 - L117 were not covered by tests
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)

Check warning on line 133 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L133

Added line #L133 was not covered by tests
}

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())
}

Check warning on line 145 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L144-L145

Added lines #L144 - L145 were not covered by tests

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

Check warning on line 162 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L158-L162

Added lines #L158 - L162 were not covered by tests
})

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)

Check warning on line 182 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L181-L182

Added lines #L181 - L182 were not covered by tests
} 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

Check warning on line 251 in slog/common.go

View check run for this annotation

Codecov / codecov/patch

slog/common.go#L250-L251

Added lines #L250 - L251 were not covered by tests
}

seen[key] = seenIndex
seenIndex++
result = append(result, item)
}

return result
}
Loading
Loading