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

[Feature] Add experiment zapslog package to integrate with slog #1246

Merged
merged 14 commits into from Mar 17, 2023
29 changes: 29 additions & 0 deletions exp/zapslog/doc.go
@@ -0,0 +1,29 @@
// Copyright (c) 2023 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// Package zapslog provides an implementation of slog.Handler which writes to
// the underlying zap.Logger.
//
// Since the slog proposal has not been officially accepted by the creation of this package,
// we do not want Zap's standard packages to take a dependency on `golang.org/x/exp/slog`.
// Instead, we provide this separate package as a way for users to integrate Zap with slog.
// For users who want to experiment Zap with slog, they can import this package and compile it with
// the build tag `zapslog`.
package zapslog // import "go.uber.org/zap/exp/slog"
knight42 marked this conversation as resolved.
Show resolved Hide resolved
69 changes: 69 additions & 0 deletions exp/zapslog/example_test.go
@@ -0,0 +1,69 @@
// Copyright (c) 2023 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//go:build zapslog
knight42 marked this conversation as resolved.
Show resolved Hide resolved

package zapslog_test

import (
"context"
"net"
"time"

"go.uber.org/zap"
"golang.org/x/exp/slog"

knight42 marked this conversation as resolved.
Show resolved Hide resolved
"go.uber.org/zap/exp/zapslog"
)

type Password string

func (p Password) LogValue() slog.Value {
return slog.StringValue("REDACTED")
}

func Example_slog() {
logger := zap.NewExample(zap.IncreaseLevel(zap.InfoLevel))
defer logger.Sync()

sl := zapslog.New(logger)

sl.Info("user", "name", "Al", "secret", Password("secret"))
sl.Error("oops", net.ErrClosed, "status", 500)
sl.LogAttrs(context.TODO(), slog.LevelError, "oops",
knight42 marked this conversation as resolved.
Show resolved Hide resolved
slog.Any("err", net.ErrClosed), slog.Int("status", 500))
sl.Info("message",
slog.Group("group",
slog.Float64("pi", 3.14),
slog.Duration("1min", time.Minute),
),
)
sl.WithGroup("s").LogAttrs(context.TODO(), slog.LevelWarn, "warn", slog.Uint64("u", 1), slog.Any("m", map[string]any{
knight42 marked this conversation as resolved.
Show resolved Hide resolved
"foo": "bar",
}))
sl.LogAttrs(context.TODO(), slog.LevelDebug, "not show up")
knight42 marked this conversation as resolved.
Show resolved Hide resolved

// Output:
// {"level":"info","msg":"user","name":"Al","secret":"REDACTED"}
// {"level":"error","msg":"oops","err":"use of closed network connection","status":500}
// {"level":"error","msg":"oops","err":"use of closed network connection","status":500}
// {"level":"info","msg":"message","group":{"pi":3.14,"1min":"1m0s"}}
// {"level":"warn","msg":"warn","s":{"u":1,"m":{"foo":"bar"}}}
}
13 changes: 13 additions & 0 deletions exp/zapslog/go.mod
@@ -0,0 +1,13 @@
module go.uber.org/zap/exp/zapslog
knight42 marked this conversation as resolved.
Show resolved Hide resolved

go 1.19

require (
go.uber.org/zap v1.24.0
golang.org/x/exp v0.0.0-20230307190834-24139beb5833
)

require (
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
)
20 changes: 20 additions & 0 deletions exp/zapslog/go.sum
@@ -0,0 +1,20 @@
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/exp v0.0.0-20230307190834-24139beb5833 h1:SChBja7BCQewoTAU7IgvucQKMIXrEpFxNMs0spT3/5s=
golang.org/x/exp v0.0.0-20230307190834-24139beb5833/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
132 changes: 132 additions & 0 deletions exp/zapslog/slog.go
@@ -0,0 +1,132 @@
// Copyright (c) 2023 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//go:build zapslog

knight42 marked this conversation as resolved.
Show resolved Hide resolved
package zapslog

import (
"context"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/slog"
)

type handler struct {
logger *zap.Logger
knight42 marked this conversation as resolved.
Show resolved Hide resolved
}

var _ slog.Handler = (*handler)(nil)

// group holds all the Attrs saved in a slog.GroupValue.
type group struct {
attrs []slog.Attr
}

func (g *group) MarshalLogObject(enc zapcore.ObjectEncoder) error {
for _, attr := range g.attrs {
knight42 marked this conversation as resolved.
Show resolved Hide resolved
convertAttrToField(attr).AddTo(enc)
}
return nil
}

func convertAttrToField(attr slog.Attr) zapcore.Field {
switch attr.Value.Kind() {
case slog.KindBool:
return zap.Bool(attr.Key, attr.Value.Bool())
case slog.KindDuration:
return zap.Duration(attr.Key, attr.Value.Duration())
case slog.KindFloat64:
return zap.Float64(attr.Key, attr.Value.Float64())
case slog.KindInt64:
return zap.Int64(attr.Key, attr.Value.Int64())
case slog.KindString:
return zap.String(attr.Key, attr.Value.String())
case slog.KindTime:
return zap.Time(attr.Key, attr.Value.Time())
case slog.KindUint64:
return zap.Uint64(attr.Key, attr.Value.Uint64())
case slog.KindGroup:
return zap.Object(attr.Key, &group{attrs: attr.Value.Group()})
case slog.KindLogValuer:
return convertAttrToField(slog.Attr{
Key: attr.Key,
Value: attr.Value.Resolve(),
})
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will resolve the LogValuer eagerly, which will hurt anyone using LogValuer to defer expensive operations.

Ideally, we want to use a wrapper struct that calls LogValue() at serialization time,
but that may not be 100% straightforward because a LogValuer doesn't know if it's a group or a primitive type until calling LogValue(),
whereas Zap wants to know that in advance.
This may require a lazy field-equivalent in Zap.
We can defer designing that to a follow-up.
CC @mway @prashantv @sywhang

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 on a adding a lazy-field equivalent in zap separately.

default:
return zap.Any(attr.Key, attr.Value.Any())
}
}

// convertSlogLevel maps slog Levels to zap Levels.
// Note that there is some room between slog levels while zap levels are continuous, so we can't 1:1 map them.
// See also https://go.googlesource.com/proposal/+/master/design/56345-structured-logging.md?pli=1#levels
func convertSlogLevel(l slog.Level) zapcore.Level {
switch {
case l >= slog.LevelError:
return zapcore.ErrorLevel
case l >= slog.LevelWarn:
return zapcore.WarnLevel
case l >= slog.LevelInfo:
return zapcore.InfoLevel
default:
return zapcore.DebugLevel
}
}

func (h *handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.logger.Core().Enabled(convertSlogLevel(level))
}

func (h *handler) Handle(ctx context.Context, record slog.Record) error {
fields := make([]zapcore.Field, 0, record.NumAttrs())
record.Attrs(func(attr slog.Attr) {
fields = append(fields, convertAttrToField(attr))
})
h.logger.Log(convertSlogLevel(record.Level), record.Message, fields...)
return nil
}

func (h *handler) WithAttrs(attrs []slog.Attr) slog.Handler {
fields := make([]zapcore.Field, len(attrs))
for i, attr := range attrs {
fields[i] = convertAttrToField(attr)
}
return &handler{
logger: h.logger.With(fields...),
}

}

func (h *handler) WithGroup(name string) slog.Handler {
return &handler{
logger: h.logger.With(zap.Namespace(name)),
}
}

// New returns a *slog.Logger which writes to the supplied zap Logger.
func New(logger *zap.Logger) *slog.Logger {
const slogCallerDepth = 1
const loggerWriterDepth = 2
knight42 marked this conversation as resolved.
Show resolved Hide resolved
return slog.New(&handler{
logger: logger.WithOptions(zap.AddCallerSkip(slogCallerDepth + loggerWriterDepth)),
})
}