logger.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "github.com/grafana/grafana/pkg/metrics"
  20. "github.com/grafana/grafana/pkg/setting"
  21. "gopkg.in/macaron.v1"
  22. )
  23. func Logger() macaron.Handler {
  24. return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
  25. start := time.Now()
  26. c.Data["perfmon.start"] = start
  27. rw := res.(macaron.ResponseWriter)
  28. c.Next()
  29. timeTakenMs := time.Since(start) / time.Millisecond
  30. if timer, ok := c.Data["perfmon.timer"]; ok {
  31. timerTyped := timer.(metrics.Timer)
  32. timerTyped.Update(timeTakenMs)
  33. }
  34. status := rw.Status()
  35. if status == 200 || status == 304 {
  36. if !setting.RouterLogging {
  37. return
  38. }
  39. }
  40. if ctx, ok := c.Data["ctx"]; ok {
  41. ctxTyped := ctx.(*Context)
  42. if status == 500 {
  43. 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())
  44. } else {
  45. 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())
  46. }
  47. }
  48. }
  49. }