logger.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/setting"
  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. uname := c.GetCookie(setting.CookieUserName)
  28. if len(uname) == 0 {
  29. uname = "-"
  30. }
  31. rw := res.(macaron.ResponseWriter)
  32. c.Next()
  33. content := fmt.Sprintf("Completed %s %s \"%s %s %s\" %v %s %d bytes in %dus", c.RemoteAddr(), uname, req.Method, req.URL.Path, req.Proto, rw.Status(), http.StatusText(rw.Status()), rw.Size(), time.Since(start)/time.Microsecond)
  34. switch rw.Status() {
  35. case 200, 304:
  36. content = fmt.Sprintf("%s", content)
  37. if !setting.RouterLogging {
  38. return
  39. }
  40. case 404:
  41. content = fmt.Sprintf("%s", content)
  42. case 500:
  43. content = fmt.Sprintf("%s", content)
  44. }
  45. log.Info(content)
  46. }
  47. }