...
1[](https://godoc.org/github.com/wojas/genericr)
2
3# genericr
4
5A generic [logr](https://github.com/go-logr/logr) implementation that makes it easy
6to write your own logging backend.
7
8This package allows you to implement the logr interface by implementing a single
9callback function instead of the full interface.
10
11## Examples
12
13### Basic example
14
15Basic example that directly writes to stderr:
16
17```go
18log := genericr.New(func(e genericr.Entry) {
19 fmt.Fprintln(os.Stderr, e.String())
20})
21
22log.WithName("some-component").WithValues("x", 123).V(1).Info("some event", "y", 42)
23```
24
25This outputs the default string representation which currently looks like this:
26
27```
28[1] some-component "some event" x=123 y=42
29```
30
31The `genericr.Entry` struct you receive in your handler contains the following fields
32that you can use to do your own formatting:
33
34```go
35type Entry struct {
36 Level int // level at which this was logged
37 Name string // name parts joined with '.'
38 NameParts []string // individual name segments
39 Message string // message as send to log call
40 Error error // error if .Error() was called
41 Fields []interface{} // alternating key-value pairs
42
43 // Caller information
44 Caller runtime.Frame // only available after .WithCaller(true)
45 CallerDepth int // caller depth from callback
46}
47```
48
49Use `e.FieldsMap()` to retrieve the Fields as a map.
50
51To enable caller information, use `genericr.New(...).WithCaller(true)`.
52
53To filter messages above a certain verbosity level, use `genericr.New(...).WithVerbosity(1)`.
54
55### Usage in tests
56
57This shows how you can redirect logs to the testing.T logger and keep a reference
58to the last log entry if you want to check that one:
59
60```go
61func TestLogger_Table(t *testing.T) {
62 var last genericr.Entry
63 log := genericr.New(func(e genericr.Entry) {
64 last = e
65 t.Log(e.String())
66 })
67 // ...
68}
69```
70
71### Logrus example
72
73More complicated example that implements a [logrus](https://github.com/sirupsen/logrus) adapter:
74
75```go
76root := logrus.New()
77root.SetLevel(logrus.TraceLevel)
78root.SetFormatter(&logrus.TextFormatter{
79 DisableColors: true,
80 DisableTimestamp: true,
81})
82root.Out = os.Stdout
83
84var lf genericr.LogFunc = func(e genericr.Entry) {
85 var l *logrus.Entry = root.WithField("component", e.Name)
86 if e.Error != nil {
87 l = l.WithError(e.Error)
88 }
89 if len(e.Fields) != 0 {
90 l = l.WithFields(e.FieldsMap())
91 }
92 logrusLevel := logrus.Level(e.Level) + logrus.InfoLevel // 0 = info
93 if logrusLevel < logrus.ErrorLevel {
94 logrusLevel = logrus.ErrorLevel
95 } else if logrusLevel > logrus.TraceLevel {
96 logrusLevel = logrus.TraceLevel
97 }
98 l.Log(logrusLevel, e.Message)
99}
100log := genericr.New(lf)
101```
102
View as plain text