( reqID string, r *http.Request, status int, err errctx.Error, additional ...slog.Attr, )
| 25 | } |
| 26 | |
| 27 | func LogResponse( |
| 28 | reqID string, |
| 29 | r *http.Request, |
| 30 | status int, |
| 31 | err errctx.Error, |
| 32 | additional ...slog.Attr, |
| 33 | ) { |
| 34 | var level slog.Level |
| 35 | |
| 36 | switch { |
| 37 | case status >= 500 || (err != nil && err.StatusCode() >= 500): |
| 38 | level = slog.LevelError |
| 39 | case status >= 400: |
| 40 | level = slog.LevelWarn |
| 41 | default: |
| 42 | level = slog.LevelInfo |
| 43 | } |
| 44 | |
| 45 | clientIP, _, _ := net.SplitHostPort(r.RemoteAddr) |
| 46 | |
| 47 | attrs := []slog.Attr{ |
| 48 | slog.String("request_id", reqID), |
| 49 | slog.String("method", r.Method), |
| 50 | slog.Int("status", status), |
| 51 | slog.String("client_ip", clientIP), |
| 52 | } |
| 53 | |
| 54 | if err != nil { |
| 55 | attrs = append(attrs, slog.Any("error", err)) |
| 56 | |
| 57 | if level >= slog.LevelError { |
| 58 | if stack := err.FormatStack(); len(stack) > 0 { |
| 59 | attrs = append(attrs, slog.String("stack", stack)) |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | attrs = append(attrs, additional...) |
| 65 | |
| 66 | slog.LogAttrs( |
| 67 | context.Background(), |
| 68 | level, |
| 69 | fmt.Sprintf("Completed in %s %s", RequestDuration(r.Context()), r.RequestURI), |
| 70 | attrs..., |
| 71 | ) |
| 72 | } |
no test coverage detected