-
Notifications
You must be signed in to change notification settings - Fork 0
/
slog.go
30 lines (26 loc) · 1.15 KB
/
slog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package wglog
import (
"fmt"
"golang.zx2c4.com/wireguard/device"
"log/slog"
"reflect"
"slices"
)
// Slog creates a [device.Logger] instance that is backed by a specified [slog.Logger].
// No args are passed to the slog logger, instead the message is created from the format string and args passed to the [device.Logger].Verbosef and [device.Logger].Errorf funcs.
// Verbose messages are logged at the Debug level, while errors are logged at the Error level.
func Slog(logger *slog.Logger) *device.Logger {
logger = elseDefault(logger, slog.Default())
return &device.Logger{
Verbosef: func(format string, args ...any) { logger.Debug(fmt.Sprintf(format, args...)) },
Errorf: func(format string, args ...any) { logger.Error(fmt.Sprintf(format, args...)) },
}
}
// validNil is a set of [reflect.Kind] that will not panic on [reflect.Value.IsNil] if [reflect.Value] is valid.
var validNil = []reflect.Kind{reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice}
func elseDefault[T any](v, def T) T {
if vv := reflect.ValueOf(v); slices.Contains(validNil, vv.Kind()) && (vv.IsZero() || vv.IsNil()) {
return def
}
return v
}