-
-
Notifications
You must be signed in to change notification settings - Fork 559
/
log.go
46 lines (41 loc) Β· 953 Bytes
/
log.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package middleware
import (
"bytes"
"fmt"
"log"
"strings"
)
type (
// Logger is the logging interface used by the middleware to produce
// log entries.
Logger interface {
// Log creates a log entry using a sequence of alternating keys
// and values.
Log(keyvals ...any) error
}
// adapter is a thin wrapper around the stdlib logger that adapts it to
// the Logger interface.
adapter struct {
*log.Logger
}
)
// NewLogger creates a Logger backed by a stdlib logger.
func NewLogger(l *log.Logger) Logger {
return &adapter{l}
}
func (a *adapter) Log(keyvals ...any) error {
n := (len(keyvals) + 1) / 2
if len(keyvals)%2 != 0 {
keyvals = append(keyvals, "MISSING")
}
var fm bytes.Buffer
vals := make([]any, n)
for i := 0; i < len(keyvals); i += 2 {
k := keyvals[i]
v := keyvals[i+1]
vals[i/2] = v
fm.WriteString(fmt.Sprintf(" %s=%%+v", k))
}
a.Logger.Printf(strings.TrimSpace(fm.String()), vals...)
return nil
}