| 1 | package zhttp |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/rs/zerolog" |
| 11 | "github.com/rs/zerolog/hlog" |
| 12 | "github.com/stretchr/testify/assert" |
| 13 | "github.com/stretchr/testify/require" |
| 14 | ) |
| 15 | |
| 16 | func TestLoggingMiddleware(t *testing.T) { |
| 17 | h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 18 | switch r.URL.Path { |
| 19 | case "/dontlog": |
| 20 | DontLog(r) |
| 21 | case "/changeme": |
| 22 | r.URL.Path = "/changed" |
| 23 | default: |
| 24 | http.NotFound(w, r) |
| 25 | return |
| 26 | } |
| 27 | // updates to the log context affect every message |
| 28 | hlog.FromRequest(r).UpdateContext(func(c zerolog.Context) zerolog.Context { |
| 29 | return c.Str("append1", "always") |
| 30 | }) |
| 31 | // append only to the access log without affecting the context |
| 32 | AppendAccessLog(r, func(e *zerolog.Event) { |
| 33 | e.Str("append2", "access") |
| 34 | }) |
| 35 | hlog.FromRequest(r).Info().Msg("a message") |
| 36 | }) |
| 37 | var buf bytes.Buffer |
| 38 | logger := zerolog.New(&buf) |
| 39 | now := fakeTime() |
| 40 | mw := LoggingMiddleware( |
| 41 | WithLogger(logger), |
| 42 | func(lc *loggingConfig) { lc.now = now }, |
| 43 | ) |
| 44 | newReq := func(path string) *http.Request { |
| 45 | r := httptest.NewRequest(http.MethodGet, path, nil) |
| 46 | r.RemoteAddr = "192.168.1.1:12345" |
| 47 | r.Header.Set("X-Request-Id", "00000000") |
| 48 | r.Header.Set("User-Agent", "unittest") |
| 49 | return r |
| 50 | } |
| 51 | |
| 52 | t.Run("Changed", func(t *testing.T) { |
| 53 | buf.Reset() |
| 54 | r, w := newReq("/changeme"), httptest.NewRecorder() |
| 55 | mw(h).ServeHTTP(w, r) |
| 56 | resp := w.Result() |
| 57 | require.Equal(t, http.StatusOK, resp.StatusCode) |
| 58 | assert.Equal(t, `{"level":"info","ip":"192.168.1.1","req_id":"00000000","append1":"always","message":"a message"} |
| 59 | {"level":"info","ip":"192.168.1.1","req_id":"00000000","append1":"always","method":"GET","url":"/changed","status":200,"len":0,"dur":1000,"ttfb":2000,"ua":"unittest","append2":"access"} |
| 60 | `, buf.String()) |
| 61 | }) |
| 62 | t.Run("DontLog", func(t *testing.T) { |
| 63 | buf.Reset() |
| 64 | r, w := newReq("/dontlog"), httptest.NewRecorder() |
| 65 | mw(h).ServeHTTP(w, r) |
| 66 | resp := w.Result() |
| 67 | require.Equal(t, http.StatusOK, resp.StatusCode) |
| 68 | assert.Equal(t, `{"level":"info","ip":"192.168.1.1","req_id":"00000000","append1":"always","message":"a message"} |
| 69 | `, buf.String()) |
| 70 | }) |
| 71 | } |
| 72 | |
| 73 | func fakeTime() func() time.Time { |
| 74 | ts := time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC) |
| 75 | return func() time.Time { |
| 76 | ts = ts.Add(time.Second) |
| 77 | return ts |
| 78 | } |
| 79 | } |