| 21 | ) |
| 22 | |
| 23 | func TestRequestLoggerOK(t *testing.T) { |
| 24 | old := slog.Default() |
| 25 | t.Cleanup(func() { |
| 26 | slog.SetDefault(old) |
| 27 | }) |
| 28 | |
| 29 | e := echo.New() |
| 30 | e.IPExtractor = echo.LegacyIPExtractor() |
| 31 | buf := new(bytes.Buffer) |
| 32 | e.Logger = slog.New(slog.NewJSONHandler(buf, nil)) |
| 33 | e.Use(RequestLogger()) |
| 34 | |
| 35 | e.POST("/test", func(c *echo.Context) error { |
| 36 | return c.String(http.StatusTeapot, "OK") |
| 37 | }) |
| 38 | |
| 39 | reader := strings.NewReader(`{"foo":"bar"}`) |
| 40 | req := httptest.NewRequest(http.MethodPost, "/test", reader) |
| 41 | req.Header.Set(echo.HeaderContentLength, strconv.Itoa(int(reader.Size()))) |
| 42 | req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) |
| 43 | req.Header.Set(echo.HeaderXRealIP, "8.8.8.8") |
| 44 | req.Header.Set("User-Agent", "curl/7.68.0") |
| 45 | |
| 46 | rec := httptest.NewRecorder() |
| 47 | e.ServeHTTP(rec, req) |
| 48 | |
| 49 | logAttrs := map[string]any{} |
| 50 | assert.NoError(t, json.Unmarshal(buf.Bytes(), &logAttrs)) |
| 51 | logAttrs["latency"] = 123 |
| 52 | logAttrs["time"] = "x" |
| 53 | |
| 54 | expect := map[string]any{ |
| 55 | "level": "INFO", |
| 56 | "msg": "REQUEST", |
| 57 | "method": "POST", |
| 58 | "uri": "/test", |
| 59 | "status": float64(418), |
| 60 | "bytes_in": "13", |
| 61 | "host": "example.com", |
| 62 | "bytes_out": float64(2), |
| 63 | "user_agent": "curl/7.68.0", |
| 64 | "remote_ip": "8.8.8.8", |
| 65 | "request_id": "", |
| 66 | |
| 67 | "time": "x", |
| 68 | "latency": 123, |
| 69 | } |
| 70 | assert.Equal(t, expect, logAttrs) |
| 71 | } |
| 72 | |
| 73 | func TestRequestLoggerError(t *testing.T) { |
| 74 | old := slog.Default() |