|
1 | 1 | package middlewares |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "net/http" |
5 | | - "time" |
| 4 | + "net/http" |
| 5 | + "time" |
6 | 6 |
|
7 | | - "go.uber.org/zap" |
| 7 | + "github.com/google/uuid" |
| 8 | + "go.uber.org/zap" |
8 | 9 | ) |
9 | 10 |
|
| 11 | +type loggingResponseWriter struct { |
| 12 | + http.ResponseWriter |
| 13 | + status int |
| 14 | + size int |
| 15 | +} |
| 16 | + |
| 17 | +func (lrw *loggingResponseWriter) WriteHeader(code int) { |
| 18 | + lrw.status = code |
| 19 | + lrw.ResponseWriter.WriteHeader(code) |
| 20 | +} |
| 21 | + |
| 22 | +func (lrw *loggingResponseWriter) Write(b []byte) (int, error) { |
| 23 | + if lrw.status == 0 { |
| 24 | + lrw.status = http.StatusOK |
| 25 | + } |
| 26 | + n, err := lrw.ResponseWriter.Write(b) |
| 27 | + lrw.size += n |
| 28 | + return n, err |
| 29 | +} |
| 30 | + |
10 | 31 | func RequestLogger(logger *zap.Logger) func(http.Handler) http.Handler { |
11 | | - return func(next http.Handler) http.Handler { |
12 | | - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
13 | | - start := time.Now() |
14 | | - next.ServeHTTP(w, r) |
15 | | - logger.Info("request", |
16 | | - zap.String("method", r.Method), |
17 | | - zap.String("path", r.URL.Path), |
18 | | - zap.Duration("dur", time.Since(start)), |
19 | | - zap.String("ua", r.UserAgent())) |
20 | | - }) |
21 | | - } |
| 32 | + return func(next http.Handler) http.Handler { |
| 33 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 34 | + start := time.Now() |
| 35 | + |
| 36 | + // Ensure we have a request ID for correlation |
| 37 | + reqID := r.Header.Get("X-Request-ID") |
| 38 | + if reqID == "" { |
| 39 | + reqID = uuid.New().String() |
| 40 | + } |
| 41 | + |
| 42 | + w.Header().Set("X-Request-ID", reqID) |
| 43 | + |
| 44 | + lrw := &loggingResponseWriter{ResponseWriter: w} |
| 45 | + next.ServeHTTP(lrw, r) |
| 46 | + |
| 47 | + if lrw.status == 0 { |
| 48 | + lrw.status = http.StatusOK |
| 49 | + } |
| 50 | + |
| 51 | + logger.Info("request", |
| 52 | + zap.String("id", reqID), |
| 53 | + zap.String("method", r.Method), |
| 54 | + zap.String("path", r.URL.Path), |
| 55 | + zap.Int("status", lrw.status), |
| 56 | + zap.Int("bytes", lrw.size), |
| 57 | + zap.Duration("dur", time.Since(start)), |
| 58 | + zap.String("ua", r.UserAgent())) |
| 59 | + }) |
| 60 | + } |
22 | 61 | } |
0 commit comments