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

feat: generate custom Logger instead of wrapping slog.Logger #12

Merged
merged 5 commits into from
Sep 25, 2023
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
5 changes: 1 addition & 4 deletions .slog.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,8 @@ imports:
# format: <name:severity>
# default: []
levels:
- trace: -8
- debug: -4
- info: 0
- warn: 4
- error: 8
- alert: 1

# the list of keys to generate constants for.
# default: []
Expand Down
65 changes: 32 additions & 33 deletions example/example.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

75 changes: 36 additions & 39 deletions sloggen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
var cfg = config{
Pkg: "test",
Imports: []string{"fmt", "log/slog", "strings", "time"},
Levels: map[int]string{-8: "custom"},
Levels: map[int]string{1: "custom"},
Consts: []string{"foo"},
Attrs: map[string]string{
"bar": "time.Time",
Expand All @@ -32,7 +32,7 @@ pkg: test
imports:
- time
levels:
- custom: -8
- custom: 1
consts:
- foo
attrs:
Expand All @@ -55,7 +55,7 @@ import "log/slog"
import "strings"
import "time"

const LevelCustom = slog.Level(-8)
const LevelCustom = slog.Level(1)

const Foo = "foo"

Expand Down Expand Up @@ -88,46 +88,43 @@ func ReplaceAttr(_ []string, attr slog.Attr) slog.Attr {
assert.Equal[E](t, buf.String(), src)
}

func TestParseLevel(t *testing.T) {
level, err := example.ParseLevel("TRACE")
assert.NoErr[F](t, err)
assert.Equal[E](t, level, example.LevelTrace)
}
func TestExample(t *testing.T) {
replaceAttr := func(groups []string, attr slog.Attr) slog.Attr {
if attr.Key == slog.TimeKey {
return slog.Attr{}
}
if attr.Key == slog.SourceKey {
src := attr.Value.Any().(*slog.Source)
src.File = filepath.Base(src.File)
}
return example.ReplaceAttr(groups, attr)
}

func TestReplaceAttr(t *testing.T) {
var buf bytes.Buffer
handler := slog.NewTextHandler(&buf, &slog.HandlerOptions{
Level: example.LevelTrace,
ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
if attr.Key == slog.TimeKey {
return slog.Attr{}
}
return example.ReplaceAttr(groups, attr)
},
AddSource: true,
Level: example.LevelInfo,
ReplaceAttr: replaceAttr,
})

logger := slog.New(handler)
logger.Log(context.Background(), example.LevelTrace, "test")
assert.Equal[E](t, buf.String(), "level=TRACE msg=test\n")
}

func TestLogger(t *testing.T) {
var buf bytes.Buffer
handler := slog.NewTextHandler(&buf, &slog.HandlerOptions{
AddSource: true,
ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
if attr.Key == slog.TimeKey {
return slog.Attr{}
}
if attr.Key == slog.SourceKey {
src := attr.Value.Any().(*slog.Source)
src.File = filepath.Base(src.File)
}
return attr
},
})
logger := example.New(handler).
WithGroup("group").
With(slog.String("key", "value"))

logger := example.Logger{Logger: slog.New(handler)}
logger.Info(context.Background(), "test")
assert.Equal[E](t, buf.String(), "level=INFO source=sloggen_test.go:131 msg=test\n")
level, err := example.ParseLevel("ALERT")
assert.NoErr[F](t, err)
assert.Equal[E](t, level, example.LevelAlert)

ctx := context.Background()
enabled := logger.Enabled(ctx, level)
assert.Equal[E](t, enabled, true)

logger.Info(ctx, "foo")
logger.Alert(ctx, "bar")
logger.Log(ctx, level, "baz")
assert.Equal[E](t, "\n"+buf.String(), `
level=INFO source=sloggen_test.go:122 msg=foo group.key=value
level=ALERT source=sloggen_test.go:123 msg=bar group.key=value
level=ALERT source=sloggen_test.go:124 msg=baz group.key=value
`)
}
56 changes: 53 additions & 3 deletions template.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,70 @@ func ReplaceAttr(_ []string, attr slog.Attr) slog.Attr {
{{end}}

{{if $l := $.Logger}}
type Logger struct{ Logger *slog.Logger }
type Logger struct{ handler slog.Handler }

func New(h slog.Handler) *Logger { return &Logger{handler: h} }

func (l *Logger) Handler() slog.Handler { return l.handler }

func (l *Logger) Enabled(ctx context.Context, level slog.Level) bool {
return l.handler.Enabled(ctx, level)
}

func (l *Logger) With({{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) *Logger {
if len({{if $l.AttrAPI}}attrs{{else}}args{{end}}) == 0 {
return l
}
return &Logger{handler: l.handler.WithAttrs({{if $l.AttrAPI}}attrs{{else}}args2attrs(args){{end}})}
}

func (l *Logger) WithGroup(name string) *Logger {
if name == "" {
return l
}
return &Logger{handler: l.handler.WithGroup(name)}
}

func (l *Logger) Log({{if $l.Context}}ctx context.Context, {{end}}level slog.Level, msg string, {{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) {
l.log({{if $l.Context}}ctx{{else}}context.Background(){{end}}, level, msg, {{if $l.AttrAPI}}attrs{{else}}args{{end}})
}

{{range $_, $name := $l.Levels}}
func (l *Logger) {{title $name}}({{if $l.Context}}ctx context.Context, {{end}}msg string, {{if $l.AttrAPI}}attrs ...slog.Attr{{else}}args ...any{{end}}) {
l.log({{if $l.Context}}ctx{{else}}context.Background(){{end}}, {{if eq (len $.Levels) 0}}slog.{{end}}Level{{title $name}}, msg, {{if $l.AttrAPI}}attrs{{else}}args{{end}})
}
{{end}}

func (l *Logger) log(ctx context.Context, level slog.Level, msg string, {{if $l.AttrAPI}}attrs []slog.Attr{{else}}args []any{{end}}) {
if !l.Logger.Enabled(ctx, level) {
if !l.handler.Enabled(ctx, level) {
return
}
var pcs [1]uintptr
runtime.Callers(3, pcs[:])
r := slog.NewRecord(time.Now(), level, msg, pcs[0])
r.Add{{if $l.AttrAPI}}Attrs(attrs...){{else}}(args...){{end}}
_ = l.Logger.Handler().Handle(ctx, r)
_ = l.handler.Handle(ctx, r)
}

{{if not $l.AttrAPI}}
{{/* based on argsToAttrSlice() and argsToAttr() from log/slog sources. */}}
func args2attrs(args []any) []slog.Attr {
var attrs []slog.Attr
for len(args) > 0 {
switch x := args[0].(type) {
case string:
if len(args) == 1 {
attrs, args = append(attrs, slog.String("!BADKEY", x)), nil
} else {
attrs, args = append(attrs, slog.Any(x, args[1])), args[2:]
}
case slog.Attr:
attrs, args = append(attrs, x), args[1:]
default:
attrs, args = append(attrs, slog.Any("!BADKEY", x)), args[1:]
}
}
return attrs
}
{{end}}
{{end}}
Loading