You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
proposal: log/slog: allow implementing slog.Handler and logr.LogSink in the same type #59110
When using a second type, conversion between LogSink and Handler has to be done through additional interfaces. That may be the right solution anyway, because it gives implementors who want to support both more flexibility.
Details
package zapr // TODO: put this into logr
import (
"github.com/go-logr/logr"
"golang.org/x/exp/slog"
)
type SlogImplementor interface {
GetSlogHandler() slog.Handler
}
type LogrImplementor interface {
GetLogrLogSink() logr.LogSink
}
// logr.ToSlog
func ToSlog(logger logr.Logger) *slog.Logger {
if slogImplementor, ok := logger.GetSink().(SlogImplementor); ok {
handler := slogImplementor.GetSlogHandler()
return slog.New(handler)
}
// TODO: implement Handler which can write to an arbitrary LogSink.
//
// Problem: LogSinks do their own stack unwinding and need to
// know how many levels to skip to get across the slog.Logger
// frontend into the user code. Probably doesn't have a good
// solution.
return nil
}
// logr.FromSlog
func FromSlog(logger *slog.Logger) logr.Logger {
if logrImplementor, ok := logger.Handler().(LogrImplementor); ok {
logSink := logrImplementor.GetLogrLogSink()
return logr.New(logSink)
}
// TODO: implement LogSink which can write to an arbitrary Handler.
//
// TBD: the stored WithName prefix has to be added to the Record.Message
// or added as a new Attr (but with which key?).
return logr.Discard()
}
Activity
pohly commentedon Mar 18, 2023
When using a second type, conversion between LogSink and Handler has to be done through additional interfaces. That may be the right solution anyway, because it gives implementors who want to support both more flexibility.
Details
xorkevin commentedon Mar 20, 2023
One could create an adapter type to wrap a
logr.LogSinkwith theslog.Handlerinterface right?jba commentedon Mar 21, 2023
I don't see us changing the name of
Enabledjust for this, and it looks like there are several ways around it.Any objection if I close this?
pohly commentedon Mar 21, 2023
Yes, let's close. I've been using the adapter type approach and it's not too bad.