Skip to content

Commit f1f6b21

Browse files
committed
feat: add logger interface and default implementation
1 parent c43197d commit f1f6b21

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

logger.go

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package viper
2+
3+
import (
4+
"fmt"
5+
6+
jww "github.com/spf13/jwalterweatherman"
7+
)
8+
9+
// Logger is a unified interface for various logging use cases and practices, including:
10+
// - leveled logging
11+
// - structured logging
12+
type Logger interface {
13+
// Trace logs a Trace event.
14+
//
15+
// Even more fine-grained information than Debug events.
16+
// Loggers not supporting this level should fall back to Debug.
17+
Trace(msg string, keyvals ...interface{})
18+
19+
// Debug logs a Debug event.
20+
//
21+
// A verbose series of information events.
22+
// They are useful when debugging the system.
23+
Debug(msg string, keyvals ...interface{})
24+
25+
// Info logs an Info event.
26+
//
27+
// General information about what's happening inside the system.
28+
Info(msg string, keyvals ...interface{})
29+
30+
// Warn logs a Warn(ing) event.
31+
//
32+
// Non-critical events that should be looked at.
33+
Warn(msg string, keyvals ...interface{})
34+
35+
// Error logs an Error event.
36+
//
37+
// Critical events that require immediate attention.
38+
// Loggers commonly provide Fatal and Panic levels above Error level,
39+
// but exiting and panicing is out of scope for a logging library.
40+
Error(msg string, keyvals ...interface{})
41+
}
42+
43+
type jwwLogger struct{}
44+
45+
func (jwwLogger) Trace(msg string, keyvals ...interface{}) {
46+
jww.TRACE.Printf(jwwLogMessage(msg, keyvals...))
47+
}
48+
49+
func (jwwLogger) Debug(msg string, keyvals ...interface{}) {
50+
jww.DEBUG.Printf(jwwLogMessage(msg, keyvals...))
51+
}
52+
53+
func (jwwLogger) Info(msg string, keyvals ...interface{}) {
54+
jww.INFO.Printf(jwwLogMessage(msg, keyvals...))
55+
}
56+
57+
func (jwwLogger) Warn(msg string, keyvals ...interface{}) {
58+
jww.WARN.Printf(jwwLogMessage(msg, keyvals...))
59+
}
60+
61+
func (jwwLogger) Error(msg string, keyvals ...interface{}) {
62+
jww.ERROR.Printf(jwwLogMessage(msg, keyvals...))
63+
}
64+
65+
func jwwLogMessage(msg string, keyvals ...interface{}) string {
66+
out := msg
67+
68+
if len(keyvals) > 0 && len(keyvals)%2 == 1 {
69+
keyvals = append(keyvals, nil)
70+
}
71+
72+
for i := 0; i <= len(keyvals)-2; i += 2 {
73+
out = fmt.Sprintf("%s %v=%v", out, keyvals[i], keyvals[i+1])
74+
}
75+
76+
return out
77+
}

0 commit comments

Comments
 (0)