-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger_test.go
73 lines (68 loc) · 2.06 KB
/
logger_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
package fox
import (
"bytes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
func TestLoggerWithHandler(t *testing.T) {
buf := bytes.NewBuffer(nil)
f := New(
WithRedirectTrailingSlash(true),
WithMiddleware(LoggerWithHandler(slog.NewTextHandler(buf, &slog.HandlerOptions{
Level: slog.LevelDebug,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "time" {
return slog.String("time", "time")
}
if a.Key == "latency" {
return slog.String("latency", "latency")
}
return a
},
}))),
)
require.NoError(t, onlyError(f.Handle(http.MethodGet, "/success", func(c Context) {
c.Writer().WriteHeader(http.StatusOK)
})))
require.NoError(t, onlyError(f.Handle(http.MethodGet, "/failure", func(c Context) {
c.Writer().WriteHeader(http.StatusInternalServerError)
})))
cases := []struct {
name string
req *http.Request
want string
}{
{
name: "should log info level",
req: httptest.NewRequest(http.MethodGet, "/success", nil),
want: "time=time level=INFO msg=192.0.2.1 status=200 method=GET host=example.com path=/success latency=latency\n",
},
{
name: "should log error level",
req: httptest.NewRequest(http.MethodGet, "/failure", nil),
want: "time=time level=ERROR msg=192.0.2.1 status=500 method=GET host=example.com path=/failure latency=latency\n",
},
{
name: "should log warn level",
req: httptest.NewRequest(http.MethodGet, "/foobar", nil),
want: "time=time level=WARN msg=192.0.2.1 status=404 method=GET host=example.com path=/foobar latency=latency\n",
},
{
name: "should log debug level",
req: httptest.NewRequest(http.MethodGet, "/success/", nil),
want: "time=time level=DEBUG msg=192.0.2.1 status=301 method=GET host=example.com path=/success/ latency=latency location=../success\n",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
buf.Reset()
w := httptest.NewRecorder()
f.ServeHTTP(w, tc.req)
assert.Equal(t, tc.want, buf.String())
})
}
}