-
Notifications
You must be signed in to change notification settings - Fork 4
/
hooks_test.go
107 lines (92 loc) · 2.5 KB
/
hooks_test.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package flume
import (
"bytes"
"errors"
"fmt"
"github.com/ansel1/merry"
"github.com/stretchr/testify/assert"
"go.uber.org/zap/zapcore"
"io/ioutil"
"testing"
)
var suppressErrVerboseOnInfoHook = func(entry *CheckedEntry, fields []Field) []Field {
for i := range fields {
if fields[i].Type == zapcore.ErrorType && entry.Level == zapcore.InfoLevel {
if err, ok := fields[i].Interface.(error); ok {
if _, ok := err.(fmt.Formatter); ok { //nolint:errorlint
err = errors.New(err.Error())
fields[i].Interface = err
}
}
}
}
return fields
}
func TestHook(t *testing.T) {
f := NewFactory()
f.SetDefaultLevel(DebugLevel)
f.Hooks(suppressErrVerboseOnInfoHook)
buf := bytes.NewBuffer(nil)
f.SetOut(buf)
// The hook should suppress the errVerbose key when the level is INF.
logger := f.NewLogger("")
logger.Error("boom", merry.New("boom"))
assert.Contains(t, buf.String(), "errorVerbose")
buf.Reset()
logger.Info("boom", merry.New("boom"))
assert.NotContains(t, buf.String(), "errorVerbose")
t.Run("ClearHooks", func(t *testing.T) {
f.ClearHooks()
buf.Reset()
logger.Info("boom", merry.New("boom"))
assert.Contains(t, buf.String(), "errorVerbose")
})
}
func TestAddHooks(t *testing.T) {
f := NewFactory()
f.SetDefaultLevel(DebugLevel)
buf := bytes.NewBuffer(nil)
f.SetOut(buf)
withoutHook := f.NewCore("withouthook")
withHook := f.NewCore("withhook", AddHooks(suppressErrVerboseOnInfoHook))
withoutHook.Info("boom", merry.New("boom"))
assert.Contains(t, buf.String(), "errorVerbose")
buf.Reset()
withHook.Info("boom", merry.New("boom"))
assert.NotContains(t, buf.String(), "errorVerbose")
}
func BenchmarkNoHook(b *testing.B) {
b.ReportAllocs()
factory := NewFactory()
factory.SetDefaultLevel(DebugLevel)
factory.SetOut(ioutil.Discard)
logger := factory.NewLogger("")
err := merry.New("boom")
for i := 0; i < b.N; i++ {
logger.Error("boom", err)
}
}
func BenchmarkHookNoop(b *testing.B) {
b.ReportAllocs()
factory := NewFactory()
factory.SetDefaultLevel(DebugLevel)
factory.SetOut(ioutil.Discard)
logger := factory.NewLogger("")
err := merry.New("boom")
factory.Hooks(suppressErrVerboseOnInfoHook)
for i := 0; i < b.N; i++ {
logger.Error("boom", err)
}
}
func BenchmarkHook(b *testing.B) {
b.ReportAllocs()
factory := NewFactory()
factory.SetDefaultLevel(DebugLevel)
factory.SetOut(ioutil.Discard)
logger := factory.NewLogger("")
err := merry.New("boom")
factory.Hooks(suppressErrVerboseOnInfoHook)
for i := 0; i < b.N; i++ {
logger.Info("boom", err)
}
}