logger.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 Unknwon
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package middleware
  16. import (
  17. "net/http"
  18. "time"
  19. m "github.com/grafana/grafana/pkg/models"
  20. "github.com/grafana/grafana/pkg/setting"
  21. "github.com/prometheus/client_golang/prometheus"
  22. "gopkg.in/macaron.v1"
  23. )
  24. func Logger() macaron.Handler {
  25. return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
  26. start := time.Now()
  27. c.Data["perfmon.start"] = start
  28. rw := res.(macaron.ResponseWriter)
  29. c.Next()
  30. timeTakenMs := time.Since(start) / time.Millisecond
  31. if timer, ok := c.Data["perfmon.timer"]; ok {
  32. timerTyped := timer.(prometheus.Summary)
  33. timerTyped.Observe(float64(timeTakenMs))
  34. }
  35. status := rw.Status()
  36. if status == 200 || status == 304 {
  37. if !setting.RouterLogging {
  38. return
  39. }
  40. }
  41. if ctx, ok := c.Data["ctx"]; ok {
  42. ctxTyped := ctx.(*m.Context)
  43. if status == 500 {
  44. ctxTyped.Logger.Error("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status, "remote_addr", c.RemoteAddr(), "time_ms", int64(timeTakenMs), "size", rw.Size(), "referer", req.Referer())
  45. } else {
  46. ctxTyped.Logger.Info("Request Completed", "method", req.Method, "path", req.URL.Path, "status", status, "remote_addr", c.RemoteAddr(), "time_ms", int64(timeTakenMs), "size", rw.Size(), "referer", req.Referer())
  47. }
  48. }
  49. }
  50. }