forked from mattermost/logr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filtercustom_test.go
91 lines (71 loc) · 2.29 KB
/
filtercustom_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
package logr_test
import (
"strings"
"sync/atomic"
"testing"
"github.com/mattermost/logr/v2"
"github.com/mattermost/logr/v2/formatters"
"github.com/mattermost/logr/v2/targets"
"github.com/mattermost/logr/v2/test"
"github.com/stretchr/testify/require"
)
var (
LoginLevel = logr.Level{ID: 250, Name: "login ", Stacktrace: false}
LogoutLevel = logr.Level{ID: 251, Name: "logout", Stacktrace: false}
BadLevel = logr.Level{ID: logr.MaxLevelID + 1, Name: "invalid", Stacktrace: false}
)
func TestCustomLevel(t *testing.T) {
lgr, _ := logr.New()
buf := &test.Buffer{}
// create a custom filter with custom levels.
filter := &logr.CustomFilter{}
filter.Add(LoginLevel, LogoutLevel)
formatter := &formatters.Plain{Delim: " | "}
target := targets.NewWriterTarget(buf)
err := lgr.AddTarget(target, "customLevelTest", filter, formatter, 1000)
require.NoError(t, err)
logger := lgr.NewLogger().With(
logr.String("user", "Bob"),
logr.String("role", "admin"),
)
logger.Log(LoginLevel, "LoginLevel will get logged")
logger.Log(logr.Error, "XXX - won't be logged as Error was not added to custom filter.")
logger.Debug("XXX - won't be logged")
logger.Log(LogoutLevel, "LogoutLevel will get logged")
err = lgr.Shutdown()
require.NoError(t, err)
output := buf.String()
t.Log(output)
if !strings.Contains(output, "LoginLevel") {
t.Error("missing LoginLevel")
}
if !strings.Contains(output, "LogoutLevel") {
t.Error("missing LogoutLevel")
}
if strings.Contains(output, "XXX") {
t.Error("wrong level(s) output")
}
}
func TestLevelIDTooLarge(t *testing.T) {
var count int32
opt := logr.OnLoggerError(func(err error) {
atomic.AddInt32(&count, 1)
})
lgr, err := logr.New(opt)
require.NoError(t, err)
buf := &test.Buffer{}
// create a custom filter with custom level.
filter := &logr.CustomFilter{}
filter.Add(BadLevel)
formatter := &formatters.Plain{Delim: " | "}
target := targets.NewWriterTarget(buf)
err = lgr.AddTarget(target, "levelTest", filter, formatter, 1000)
require.NoError(t, err)
logger := lgr.NewLogger().With(logr.String("user", "Bob"), logr.String("role", "admin"))
logger.Log(BadLevel, "this item will trigger OnLoggerError")
err = lgr.Shutdown()
require.NoError(t, err)
if atomic.LoadInt32(&count) != 1 {
t.Error("OnLoggerError should be called once")
}
}