...
1
2
3 package hlog_test
4
5 import (
6 "net/http"
7 "os"
8 "time"
9
10 "net/http/httptest"
11
12 "github.com/rs/zerolog"
13 "github.com/rs/zerolog/hlog"
14 )
15
16
17 type middleware func(http.Handler) http.Handler
18 type alice struct {
19 m []middleware
20 }
21
22 func (a alice) Append(m middleware) alice {
23 a.m = append(a.m, m)
24 return a
25 }
26 func (a alice) Then(h http.Handler) http.Handler {
27 for i := range a.m {
28 h = a.m[len(a.m)-1-i](h)
29 }
30 return h
31 }
32
33 func init() {
34 zerolog.TimestampFunc = func() time.Time {
35 return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC)
36 }
37 }
38
39 func Example_handler() {
40 log := zerolog.New(os.Stdout).With().
41 Timestamp().
42 Str("role", "my-service").
43 Str("host", "local-hostname").
44 Logger()
45
46 c := alice{}
47
48
49 c = c.Append(hlog.NewHandler(log))
50
51
52
53 c = c.Append(hlog.RemoteAddrHandler("ip"))
54 c = c.Append(hlog.UserAgentHandler("user_agent"))
55 c = c.Append(hlog.RefererHandler("referer"))
56
57
58
59 h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
60
61
62
63 hlog.FromRequest(r).Info().
64 Str("user", "current user").
65 Str("status", "ok").
66 Msg("Something happened")
67 }))
68 http.Handle("/", h)
69
70 h.ServeHTTP(httptest.NewRecorder(), &http.Request{})
71
72
73 }
74
View as plain text