| 1 |
// Copyright (c) 2023 Uber Technologies, Inc. |
| 2 |
// |
| 3 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 |
// of this software and associated documentation files (the "Software"), to deal |
| 5 |
// in the Software without restriction, including without limitation the rights |
| 6 |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 |
// copies of the Software, and to permit persons to whom the Software is |
| 8 |
// furnished to do so, subject to the following conditions: |
| 9 |
// |
| 10 |
// The above copyright notice and this permission notice shall be included in |
| 11 |
// all copies or substantial portions of the Software. |
| 12 |
// |
| 13 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 |
// THE SOFTWARE. |
| 20 |
|
| 21 |
//go:build go1.21 |
| 22 |
|
| 23 |
package zapslog |
| 24 |
|
| 25 |
import ( |
| 26 |
"context" |
| 27 |
"log/slog" |
| 28 |
"runtime" |
| 29 |
|
| 30 |
"go.uber.org/zap" |
| 31 |
"go.uber.org/zap/internal/stacktrace" |
| 32 |
"go.uber.org/zap/zapcore" |
| 33 |
) |
| 34 |
|
| 35 |
// Handler implements the slog.Handler by writing to a zap Core. |
| 36 |
type Handler struct { |
| 37 |
core zapcore.Core |
| 38 |
name string // logger name |
| 39 |
addCaller bool |
| 40 |
addStackAt slog.Level |
| 41 |
callerSkip int |
| 42 |
|
| 43 |
// List of unapplied groups. |
| 44 |
// |
| 45 |
// These are applied only if we encounter a real field |
| 46 |
// to avoid creating empty namespaces -- which is disallowed by slog's |
| 47 |
// usage contract. |
| 48 |
groups []string |
| 49 |
} |
| 50 |
|
| 51 |
// NewHandler builds a [Handler] that writes to the supplied [zapcore.Core] |
| 52 |
// with options. |
| 53 |
func NewHandler(core zapcore.Core, opts ...HandlerOption) *Handler { |
| 54 |
h := &Handler{ |
| 55 |
core: core, |
| 56 |
addStackAt: slog.LevelError, |
| 57 |
} |
| 58 |
for _, v := range opts { |
| 59 |
v.apply(h) |
| 60 |
} |
| 61 |
return h |
| 62 |
} |
| 63 |
|
| 64 |
var _ slog.Handler = (*Handler)(nil) |
| 65 |
|
| 66 |
// groupObject holds all the Attrs saved in a slog.GroupValue. |
| 67 |
type groupObject []slog.Attr |
| 68 |
|
| 69 |
func (gs groupObject) MarshalLogObject(enc zapcore.ObjectEncoder) error { |
| 70 |
for _, attr := range gs { |
| 71 |
convertAttrToField(attr).AddTo(enc) |
| 72 |
} |
| 73 |
return nil |
| 74 |
} |
| 75 |
|
| 76 |
func convertAttrToField(attr slog.Attr) zapcore.Field { |
| 77 |
if attr.Equal(slog.Attr{}) { |
| 78 |
// Ignore empty attrs. |
| 79 |
return zap.Skip() |
| 80 |
} |
| 81 |
|
| 82 |
switch attr.Value.Kind() { |
| 83 |
case slog.KindBool: |
| 84 |
return zap.Bool(attr.Key, attr.Value.Bool()) |
| 85 |
case slog.KindDuration: |
| 86 |
return zap.Duration(attr.Key, attr.Value.Duration()) |
| 87 |
case slog.KindFloat64: |
| 88 |
return zap.Float64(attr.Key, attr.Value.Float64()) |
| 89 |
case slog.KindInt64: |
| 90 |
return zap.Int64(attr.Key, attr.Value.Int64()) |
| 91 |
case slog.KindString: |
| 92 |
return zap.String(attr.Key, attr.Value.String()) |
| 93 |
case slog.KindTime: |
| 94 |
return zap.Time(attr.Key, attr.Value.Time()) |
| 95 |
case slog.KindUint64: |
| 96 |
return zap.Uint64(attr.Key, attr.Value.Uint64()) |
| 97 |
case slog.KindGroup: |
| 98 |
if attr.Key == "" { |
| 99 |
// Inlines recursively. |
| 100 |
return zap.Inline(groupObject(attr.Value.Group())) |
| 101 |
} |
| 102 |
return zap.Object(attr.Key, groupObject(attr.Value.Group())) |
| 103 |
case slog.KindLogValuer: |
| 104 |
return convertAttrToField(slog.Attr{ |
| 105 |
Key: attr.Key, |
| 106 |
// TODO: resolve the value in a lazy way. |
| 107 |
// This probably needs a new Zap field type |
| 108 |
// that can be resolved lazily. |
| 109 |
Value: attr.Value.Resolve(), |
| 110 |
}) |
| 111 |
default: |
| 112 |
return zap.Any(attr.Key, attr.Value.Any()) |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
// convertSlogLevel maps slog Levels to zap Levels. |
| 117 |
// Note that there is some room between slog levels while zap levels are continuous, so we can't 1:1 map them. |
| 118 |
// See also https://go.googlesource.com/proposal/+/master/design/56345-structured-logging.md?pli=1#levels |
| 119 |
func convertSlogLevel(l slog.Level) zapcore.Level { |
| 120 |
switch { |
| 121 |
case l >= slog.LevelError: |
| 122 |
return zapcore.ErrorLevel |
| 123 |
case l >= slog.LevelWarn: |
| 124 |
return zapcore.WarnLevel |
| 125 |
case l >= slog.LevelInfo: |
| 126 |
return zapcore.InfoLevel |
| 127 |
default: |
| 128 |
return zapcore.DebugLevel |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
// Enabled reports whether the handler handles records at the given level. |
| 133 |
func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool { |
| 134 |
return h.core.Enabled(convertSlogLevel(level)) |
| 135 |
} |
| 136 |
|
| 137 |
// Handle handles the Record. |
| 138 |
func (h *Handler) Handle(ctx context.Context, record slog.Record) error { |
| 139 |
ent := zapcore.Entry{ |
| 140 |
Level: convertSlogLevel(record.Level), |
| 141 |
Time: record.Time, |
| 142 |
Message: record.Message, |
| 143 |
LoggerName: h.name, |
| 144 |
} |
| 145 |
ce := h.core.Check(ent, nil) |
| 146 |
if ce == nil { |
| 147 |
return nil |
| 148 |
} |
| 149 |
|
| 150 |
if h.addCaller && record.PC != 0 { |
| 151 |
frame, _ := runtime.CallersFrames([]uintptr{record.PC}).Next() |
| 152 |
if frame.PC != 0 { |
| 153 |
ce.Caller = zapcore.EntryCaller{ |
| 154 |
Defined: true, |
| 155 |
PC: frame.PC, |
| 156 |
File: frame.File, |
| 157 |
Line: frame.Line, |
| 158 |
Function: frame.Function, |
| 159 |
} |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
if record.Level >= h.addStackAt { |
| 164 |
// Skipping 3: |
| 165 |
// zapslog/handler log/slog.(*Logger).log |
| 166 |
// slog/logger log/slog.(*Logger).log |
| 167 |
// slog/logger log/slog.(*Logger).<level> |
| 168 |
ce.Stack = stacktrace.Take(3 + h.callerSkip) |
| 169 |
} |
| 170 |
|
| 171 |
fields := make([]zapcore.Field, 0, record.NumAttrs()+len(h.groups)) |
| 172 |
|
| 173 |
var addedNamespace bool |
| 174 |
record.Attrs(func(attr slog.Attr) bool { |
| 175 |
f := convertAttrToField(attr) |
| 176 |
if !addedNamespace && len(h.groups) > 0 && f != zap.Skip() { |
| 177 |
// Namespaces are added only if at least one field is present |
| 178 |
// to avoid creating empty groups. |
| 179 |
fields = h.appendGroups(fields) |
| 180 |
addedNamespace = true |
| 181 |
} |
| 182 |
fields = append(fields, f) |
| 183 |
return true |
| 184 |
}) |
| 185 |
|
| 186 |
ce.Write(fields...) |
| 187 |
return nil |
| 188 |
} |
| 189 |
|
| 190 |
func (h *Handler) appendGroups(fields []zapcore.Field) []zapcore.Field { |
| 191 |
for _, g := range h.groups { |
| 192 |
fields = append(fields, zap.Namespace(g)) |
| 193 |
} |
| 194 |
return fields |
| 195 |
} |
| 196 |
|
| 197 |
// WithAttrs returns a new Handler whose attributes consist of |
| 198 |
// both the receiver's attributes and the arguments. |
| 199 |
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 200 |
fields := make([]zapcore.Field, 0, len(attrs)+len(h.groups)) |
| 201 |
var addedNamespace bool |
| 202 |
for _, attr := range attrs { |
| 203 |
f := convertAttrToField(attr) |
| 204 |
if !addedNamespace && len(h.groups) > 0 && f != zap.Skip() { |
| 205 |
// Namespaces are added only if at least one field is present |
| 206 |
// to avoid creating empty groups. |
| 207 |
fields = h.appendGroups(fields) |
| 208 |
addedNamespace = true |
| 209 |
} |
| 210 |
fields = append(fields, f) |
| 211 |
} |
| 212 |
|
| 213 |
cloned := *h |
| 214 |
cloned.core = h.core.With(fields) |
| 215 |
if addedNamespace { |
| 216 |
// These groups have been applied so we can clear them. |
| 217 |
cloned.groups = nil |
| 218 |
} |
| 219 |
return &cloned |
| 220 |
} |
| 221 |
|
| 222 |
// WithGroup returns a new Handler with the given group appended to |
| 223 |
// the receiver's existing groups. |
| 224 |
func (h *Handler) WithGroup(group string) slog.Handler { |
| 225 |
newGroups := make([]string, len(h.groups)+1) |
| 226 |
copy(newGroups, h.groups) |
| 227 |
newGroups[len(h.groups)] = group |
| 228 |
|
| 229 |
cloned := *h |
| 230 |
cloned.groups = newGroups |
| 231 |
return &cloned |
| 232 |
} |