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
13 changes: 13 additions & 0 deletions exp/go.mod
@@ -0,0 +1,13 @@
module go.uber.org/zap/exp

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/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=
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
68 changes: 68 additions & 0 deletions exp/zapslog/example_test.go
@@ -0,0 +1,68 @@
// 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_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 := slog.New(zapslog.NewHandler(logger.Core()))
ctx := context.Background()

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

// 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"}}}
}
145 changes: 145 additions & 0 deletions exp/zapslog/slog.go
@@ -0,0 +1,145 @@
// 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

import (
"context"

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

// Handler implements the slog.Handler by writing to a zap Core.
type Handler struct {
core zapcore.Core
}

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

// groupObject holds all the Attrs saved in a slog.GroupValue.
type groupObject []slog.Attr

func (gs groupObject) MarshalLogObject(enc zapcore.ObjectEncoder) error {
for _, attr := range gs {
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, groupObject(attr.Value.Group()))
case slog.KindLogValuer:
return convertAttrToField(slog.Attr{
Key: attr.Key,
// FIXME(knight42): resolve the value in a lazy way
Value: attr.Value.Resolve(),
})
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.core.Enabled(convertSlogLevel(level))
}

func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
ent := zapcore.Entry{
Level: convertSlogLevel(record.Level),
Time: record.Time,
Message: record.Message,
// FIXME: do we need to set the following fields?
// LoggerName:
// Caller:
// Stack:
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

cc @abhinav . Do we need to complete the Entry?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Those three fields are optional. We can start without them.
I can see Caller and LoggerName being filled in the future.
(We could probably fill the Caller from Record.PC,
but doing that cheaply adds some complexity so we can do without for now.)

However, this does bring up the need for customization.
A plain NewHandler may not be sufficient for that.

I've pushed a change to your branch with the following new API:

type HandlerOptions struct{ LoggerName string }

func (HandlerOptions) New(zapcore.Core) *Handler

The func NewHandler(..) just calls this now to get default options.
This mirrors the JSONHandler, NewJSONHandler, HandlerOptions setup.

This leaves us room for future customization llke:
opting into adding a caller name, custom level mapping, etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you! The HandlerOptions is commonly used for customization, though I thought we might want to consistently follow the functional options pattern in zap.

I can see Caller and LoggerName being filled in the future.
(We could probably fill the Caller from Record.PC,

After some trial & error, I found I could add the Caller in this PR as well, plz see the commit 1ae5945

ce := h.core.Check(ent, nil)
if ce == nil {
return nil
}

fields := make([]zapcore.Field, 0, record.NumAttrs())
record.Attrs(func(attr slog.Attr) {
fields = append(fields, convertAttrToField(attr))
})
ce.Write(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 h.withFields(fields...)

}

func (h *Handler) WithGroup(group string) slog.Handler {
return h.withFields(zap.Namespace(group))
}

// withFields returns a cloned Handler with the given fields.
func (h *Handler) withFields(fields ...zapcore.Field) *Handler {
return &Handler{
core: h.core.With(fields),
}
}

// NewHandler returns a *Handler which writes to the supplied zap Core.
func NewHandler(core zapcore.Core) *Handler {
return &Handler{
core: core,
}
}