-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Update to work with released log/slog #1320
Merged
+331
−7
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
e73c209
Update to work with released log/slog
shreyner dcecb02
Work with older versions of golang
jcmuller 1dde67e
Lower minimum-required Go version to 1.20
abhinav 7507ce2
Rename files to pre_go120 or go120, update doc.go
abhinav 14f73c5
Move build tag below copyright notice
abhinav 26ad5a6
Only 1.19 and up are supported
jcmuller 20f72ca
Revert version bump
jcmuller c5bd515
Update honnef tools
jcmuller 62ba034
Merge branch 'master' into work-with-older-versions
abhinav 4d5fbfb
Fix renames (1.21, not 1.20), simplify constraints
abhinav 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,79 @@ | ||
// 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 go1.21 | ||
|
||
package zapslog_test | ||
|
||
import ( | ||
"context" | ||
"log/slog" | ||
"net" | ||
"time" | ||
|
||
"go.uber.org/zap" | ||
"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(), nil /* options */)) | ||
ctx := context.Background() | ||
|
||
sl.Info("user", "name", "Al", "secret", Password("secret")) | ||
sl.Error("oops", "err", net.ErrClosed, "status", 500) | ||
sl.LogAttrs( | ||
ctx, | ||
slog.LevelError, | ||
"oops", | ||
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( | ||
ctx, | ||
slog.LevelWarn, | ||
"warn msg", // message | ||
slog.Uint64("u", 1), | ||
slog.Any("m", map[string]any{ | ||
"foo": "bar", | ||
})) | ||
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 msg","s":{"u":1,"m":{"foo":"bar"}}} | ||
} |
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,190 @@ | ||
// 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 go1.21 | ||
|
||
package zapslog | ||
|
||
import ( | ||
"context" | ||
"log/slog" | ||
"runtime" | ||
|
||
"go.uber.org/zap" | ||
"go.uber.org/zap/zapcore" | ||
) | ||
|
||
// Handler implements the slog.Handler by writing to a zap Core. | ||
type Handler struct { | ||
core zapcore.Core | ||
name string // logger name | ||
addSource bool | ||
} | ||
|
||
// HandlerOptions are options for a Zap-based [slog.Handler]. | ||
type HandlerOptions struct { | ||
// LoggerName is used for log entries received from slog. | ||
// | ||
// Defaults to empty. | ||
LoggerName string | ||
|
||
// AddSource configures the handler to annotate each message with the filename, | ||
// line number, and function name. | ||
// AddSource is false by default to skip the cost of computing | ||
// this information. | ||
AddSource bool | ||
} | ||
|
||
// NewHandler builds a [Handler] that writes to the supplied [zapcore.Core] | ||
// with the default options. | ||
func NewHandler(core zapcore.Core, opts *HandlerOptions) *Handler { | ||
if opts == nil { | ||
opts = &HandlerOptions{} | ||
} | ||
return &Handler{ | ||
core: core, | ||
name: opts.LoggerName, | ||
addSource: opts.AddSource, | ||
} | ||
} | ||
|
||
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, | ||
// TODO: resolve the value in a lazy way. | ||
// This probably needs a new Zap field type | ||
// that can be resolved lazily. | ||
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 | ||
} | ||
} | ||
|
||
// Enabled reports whether the handler handles records at the given level. | ||
func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool { | ||
return h.core.Enabled(convertSlogLevel(level)) | ||
} | ||
|
||
// Handle handles the Record. | ||
func (h *Handler) Handle(ctx context.Context, record slog.Record) error { | ||
ent := zapcore.Entry{ | ||
Level: convertSlogLevel(record.Level), | ||
Time: record.Time, | ||
Message: record.Message, | ||
LoggerName: h.name, | ||
// TODO: do we need to set the following fields? | ||
// Stack: | ||
} | ||
ce := h.core.Check(ent, nil) | ||
if ce == nil { | ||
return nil | ||
} | ||
|
||
if h.addSource && record.PC != 0 { | ||
frame, _ := runtime.CallersFrames([]uintptr{record.PC}).Next() | ||
if frame.PC != 0 { | ||
ce.Caller = zapcore.EntryCaller{ | ||
Defined: true, | ||
PC: frame.PC, | ||
File: frame.File, | ||
Line: frame.Line, | ||
Function: frame.Function, | ||
} | ||
} | ||
} | ||
|
||
fields := make([]zapcore.Field, 0, record.NumAttrs()) | ||
record.Attrs(func(attr slog.Attr) bool { | ||
fields = append(fields, convertAttrToField(attr)) | ||
return true | ||
}) | ||
ce.Write(fields...) | ||
return nil | ||
} | ||
|
||
// WithAttrs returns a new Handler whose attributes consist of | ||
// both the receiver's attributes and the arguments. | ||
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should probably be covered before we consider upgrading this package to the main Zap module. |
||
fields := make([]zapcore.Field, len(attrs)) | ||
for i, attr := range attrs { | ||
fields[i] = convertAttrToField(attr) | ||
} | ||
return h.withFields(fields...) | ||
} | ||
|
||
// WithGroup returns a new Handler with the given group appended to | ||
// the receiver's existing groups. | ||
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 { | ||
cloned := *h | ||
cloned.core = h.core.With(fields) | ||
return &cloned | ||
} |
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,50 @@ | ||
// 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 go1.21 | ||
|
||
package zapslog | ||
|
||
import ( | ||
"log/slog" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/require" | ||
"go.uber.org/zap/zapcore" | ||
"go.uber.org/zap/zaptest/observer" | ||
) | ||
|
||
func TestAddSource(t *testing.T) { | ||
r := require.New(t) | ||
fac, logs := observer.New(zapcore.DebugLevel) | ||
sl := slog.New(NewHandler(fac, &HandlerOptions{ | ||
AddSource: true, | ||
})) | ||
sl.Info("msg") | ||
|
||
r.Len(logs.AllUntimed(), 1, "Expected exactly one entry to be logged") | ||
entry := logs.AllUntimed()[0] | ||
r.Equal("msg", entry.Message, "Unexpected message") | ||
r.Regexp( | ||
`/slog_go121_test.go:\d+$`, | ||
entry.Caller.String(), | ||
"Unexpected caller annotation.", | ||
) | ||
} |
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
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.
We probably need a slogtest to check that the handler is right.
https://pkg.go.dev/testing/slogtest#TestHandler