//go:build go1.21// +build go1.21/*Copyright 2023 The logr Authors.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.*/package funcrimport ()var _ logr.SlogSink = &fnlogger{}const extraSlogSinkDepth = 3// 2 for slog, 1 for SlogSinkfunc ( fnlogger) ( context.Context, slog.Record) error { := make([]any, 0, 2*.NumAttrs()) .Attrs(func( slog.Attr) bool { = attrToKVs(, )returntrue })if .Level >= slog.LevelError { .WithCallDepth(extraSlogSinkDepth).Error(nil, .Message, ...) } else { := .levelFromSlog(.Level) .WithCallDepth(extraSlogSinkDepth).Info(, .Message, ...) }returnnil}func ( fnlogger) ( []slog.Attr) logr.SlogSink { := make([]any, 0, 2*len())for , := range { = attrToKVs(, ) } .AddValues()return &}func ( fnlogger) ( string) logr.SlogSink { .startGroup()return &}// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups// and other details of slog.func attrToKVs( slog.Attr, []any) []any { := .Value.Resolve()if .Kind() == slog.KindGroup { := .Group() := make([]any, 0, 2*len())for , := range { = (, ) }if .Key == "" {// slog says we have to inline these = append(, ...) } else { = append(, .Key, PseudoStruct()) } } elseif .Key != "" { = append(, .Key, .Any()) }return}// levelFromSlog adjusts the level by the logger's verbosity and negates it.// It ensures that the result is >= 0. This is necessary because the result is// passed to a LogSink and that API did not historically document whether// levels could be negative or what that meant.//// Some example usage://// logrV0 := getMyLogger()// logrV2 := logrV0.V(2)// slogV2 := slog.New(logr.ToSlogHandler(logrV2))// slogV2.Debug("msg") // =~ logrV2.V(4) =~ logrV0.V(6)// slogV2.Info("msg") // =~ logrV2.V(0) =~ logrV0.V(2)// slogv2.Warn("msg") // =~ logrV2.V(-4) =~ logrV0.V(0)func ( fnlogger) ( slog.Level) int { := -if < 0 { = 0// because LogSink doesn't expect negative V levels }returnint()}
The pages are generated with Goldsv0.8.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.