handler.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package logger
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. type handler struct {
  11. h http.Handler
  12. w io.Writer
  13. c chan logMsg
  14. }
  15. func (this handler) log(w *writer, r *http.Request) {
  16. rip := r.RemoteAddr
  17. if r.Header.Get("X-Real-IP") != "" && len(r.Header.Get("X-Real-IP")) <= 25 {
  18. rip = rip + ", " + strings.TrimSpace(r.Header.Get("X-Real-IP"))
  19. } else if r.Header.Get("X-Forwarded-For") != "" && len(r.Header.Get("X-Forwarded-For")) <= 25 {
  20. rip = rip + ", " + strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
  21. }
  22. uagent := "-"
  23. if r.Header.Get("User-Agent") != "" && len(r.Header.Get("User-Agent")) <= 256 {
  24. uagent = strings.TrimSpace(r.Header.Get("User-Agent"))
  25. }
  26. msg := fmt.Sprint(strings.Join([]string{
  27. r.Host,
  28. "(" + rip + ")",
  29. "[" + w.s.Format(time.RFC3339) + "]",
  30. `"` + r.Method,
  31. r.RequestURI,
  32. r.Proto + `"`,
  33. strconv.Itoa(w.status),
  34. strconv.Itoa(w.size),
  35. fmt.Sprintf("%.3f ms", time.Now().Sub(w.s).Seconds()),
  36. `"` + uagent + `"`,
  37. }, " "))
  38. select {
  39. case this.c <- logMsg{r.Host, msg, w.status >= 400}:
  40. return
  41. case <-time.After(1 * time.Second):
  42. fmt.Println("Logger error, log channel is overflowed (2)")
  43. return
  44. }
  45. }
  46. func (this handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  47. wrt := &writer{w: w, s: time.Now()}
  48. this.h.ServeHTTP(wrt, r)
  49. this.log(wrt, r)
  50. }