handler.go 876 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. msg := fmt.Sprint(strings.Join([]string{
  17. r.Host,
  18. r.RemoteAddr,
  19. "-",
  20. "[" + w.s.Format(time.RFC3339) + "]",
  21. `"` + r.Method,
  22. r.RequestURI,
  23. r.Proto + `"`,
  24. strconv.Itoa(w.status),
  25. strconv.Itoa(w.size),
  26. fmt.Sprintf("%.3f ms", time.Now().Sub(w.s).Seconds()/1e6),
  27. }, " "))
  28. // Do not wait
  29. go func() {
  30. select {
  31. case this.c <- logMsg{r.Host, msg, w.status >= 400}:
  32. return
  33. case <-time.After(1 * time.Second):
  34. fmt.Println("Logger error, log channel is overflowed (2)")
  35. return
  36. }
  37. }()
  38. }
  39. func (this handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  40. wrt := &writer{w: w, s: time.Now()}
  41. this.h.ServeHTTP(wrt, r)
  42. this.log(wrt, r)
  43. }