logger.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. "fmt"
  18. "net/http"
  19. "time"
  20. "github.com/grafana/grafana/pkg/log"
  21. "github.com/grafana/grafana/pkg/metrics"
  22. "github.com/grafana/grafana/pkg/setting"
  23. "gopkg.in/macaron.v1"
  24. )
  25. func Logger() macaron.Handler {
  26. return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
  27. start := time.Now()
  28. c.Data["perfmon.start"] = start
  29. uname := c.GetCookie(setting.CookieUserName)
  30. if len(uname) == 0 {
  31. uname = "-"
  32. }
  33. rw := res.(macaron.ResponseWriter)
  34. c.Next()
  35. timeTakenMs := time.Since(start) / time.Millisecond
  36. content := fmt.Sprintf("Completed %s %s \"%s %s %s\" %v %s %d bytes in %dms", c.RemoteAddr(), uname, req.Method, req.URL.Path, req.Proto, rw.Status(), http.StatusText(rw.Status()), rw.Size(), timeTakenMs)
  37. if timer, ok := c.Data["perfmon.timer"]; ok {
  38. timerTyped := timer.(metrics.Timer)
  39. timerTyped.Update(timeTakenMs)
  40. }
  41. switch rw.Status() {
  42. case 200, 304:
  43. content = fmt.Sprintf("%s", content)
  44. if !setting.RouterLogging {
  45. return
  46. }
  47. case 404:
  48. content = fmt.Sprintf("%s", content)
  49. case 500:
  50. content = fmt.Sprintf("%s", content)
  51. }
  52. log.Info(content)
  53. }
  54. }