logger.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package handlers
  2. import (
  3. "net/http"
  4. "strings"
  5. "time"
  6. "codeberg.org/vnpower/pixivfe/v2/audit"
  7. "codeberg.org/vnpower/pixivfe/v2/config"
  8. "codeberg.org/vnpower/pixivfe/v2/request_context"
  9. )
  10. type ResponseWriterInterceptStatus struct {
  11. statusCode int
  12. http.ResponseWriter
  13. }
  14. func (w *ResponseWriterInterceptStatus) WriteHeader(code int) {
  15. w.statusCode = code
  16. w.ResponseWriter.WriteHeader(code)
  17. }
  18. func CanRequestSkipLogger(r *http.Request) bool {
  19. // return false
  20. path := r.URL.Path
  21. return strings.HasPrefix(path, "/img/") ||
  22. strings.HasPrefix(path, "/css/") ||
  23. strings.HasPrefix(path, "/js/") ||
  24. strings.HasPrefix(path, "/diagnostics") ||
  25. (config.GlobalConfig.InDevelopment &&
  26. (strings.HasPrefix(path, "/proxy/s.pximg.net/") || strings.HasPrefix(path, "/proxy/i.pximg.net/")))
  27. }
  28. func LogRequest(h http.Handler) http.Handler {
  29. return http.HandlerFunc(func(w_ http.ResponseWriter, r *http.Request) {
  30. if CanRequestSkipLogger(r) {
  31. h.ServeHTTP(w_, r)
  32. } else {
  33. w := &ResponseWriterInterceptStatus{
  34. statusCode: 0,
  35. ResponseWriter: w_,
  36. }
  37. // set user context
  38. start_time := time.Now()
  39. h.ServeHTTP(w, r)
  40. end_time := time.Now()
  41. audit.LogServerRoundTrip(audit.ServedRequestSpan{
  42. StartTime: start_time,
  43. EndTime: end_time,
  44. RequestId: request_context.Get(r).RequestId,
  45. Method: r.Method,
  46. Path: r.URL.Path,
  47. Status: w.statusCode,
  48. Referer: r.Referer(),
  49. RemoteAddr: r.RemoteAddr,
  50. Error: request_context.Get(r).CaughtError,
  51. })
  52. }
  53. })
  54. }