-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsafe_handler_test.go
54 lines (45 loc) · 1.71 KB
/
safe_handler_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
package clog
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestErrorShouldSendToBackup(t *testing.T) {
backup := NewMemoryHandler()
handler := NewSafeHandler(NewDiscardHandler(), backup)
err := handler.LogEntry(LogEntry{})
assert.NoError(t, err)
assert.Len(t, backup.log, 1)
}
func TestDoubleErrorShouldReturnError(t *testing.T) {
handler := NewSafeHandler(NewDiscardHandler(), NewDiscardHandler())
err := handler.LogEntry(LogEntry{})
assert.Error(t, err)
}
func TestSafeHandlerShouldFailPrimaryHandler(t *testing.T) {
handler := NewSafeHandler(nil, NewDiscardHandler())
err := handler.LogEntry(LogEntry{})
assert.Error(t, err)
}
func TestSafeHandlerShouldFailSecondaryHandler(t *testing.T) {
handler := NewSafeHandler(NewDiscardHandler(), nil)
err := handler.LogEntry(LogEntry{})
assert.Error(t, err)
}
func TestSafeHandlerCanCanSetPrefix(t *testing.T) {
memHandler := NewMemoryHandler()
filter := NewSafeHandler(memHandler, memHandler)
filter.SetPrefix("_test_")
err := filter.LogEntry(NewLogEntry(3, LevelInfo, "hello world"))
assert.NoError(t, err)
assert.Equal(t, "_test_hello world", memHandler.log[0])
}
func ExampleSafeHandler() {
// a safe handler is a middleware with two targets (Handler):
// - it will send all messages to the primary handler
// - it will only send the messages again to the backup handler if the primary returned an error
// let's create a safe handler with these two targets: a DiscardHandler and a TextHandler
// the DiscardHandler is a special handler that always discards your log messages and returns an error
logger := NewLogger(NewSafeHandler(NewDiscardHandler(), NewTextHandler("backup ", 0)))
logger.Infof("hello %s", "world")
// Output: backup hello world
}