1
0

logging.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net"
  7. "net/http"
  8. "github.com/imgproxy/imgproxy/v3/ierrors"
  9. )
  10. func LogRequest(reqID string, r *http.Request) {
  11. path := r.RequestURI
  12. clientIP, _, _ := net.SplitHostPort(r.RemoteAddr)
  13. slog.Info(
  14. fmt.Sprintf("Started %s", path),
  15. "request_id", reqID,
  16. "method", r.Method,
  17. "client_ip", clientIP,
  18. )
  19. }
  20. func LogResponse(reqID string, r *http.Request, status int, err *ierrors.Error, additional ...slog.Attr) {
  21. var level slog.Level
  22. switch {
  23. case status >= 500 || (err != nil && err.StatusCode() >= 500):
  24. level = slog.LevelError
  25. case status >= 400:
  26. level = slog.LevelWarn
  27. default:
  28. level = slog.LevelInfo
  29. }
  30. clientIP, _, _ := net.SplitHostPort(r.RemoteAddr)
  31. attrs := []slog.Attr{
  32. slog.String("request_id", reqID),
  33. slog.String("method", r.Method),
  34. slog.Int("status", status),
  35. slog.String("client_ip", clientIP),
  36. }
  37. if err != nil {
  38. attrs = append(attrs, slog.String("error", err.Error()))
  39. if level >= slog.LevelError {
  40. if stack := err.FormatStack(); len(stack) > 0 {
  41. attrs = append(attrs, slog.String("stack", stack))
  42. }
  43. }
  44. }
  45. attrs = append(attrs, additional...)
  46. slog.LogAttrs(
  47. context.Background(),
  48. level,
  49. fmt.Sprintf("Completed in %s %s", requestStartedAt(r.Context()), r.RequestURI),
  50. attrs...,
  51. )
  52. }