logger.go 1.6 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. "fmt"
  18. "net/http"
  19. "runtime"
  20. "time"
  21. "github.com/Unknwon/macaron"
  22. "github.com/torkelo/grafana-pro/pkg/log"
  23. )
  24. var isWindows bool
  25. func init() {
  26. isWindows = runtime.GOOS == "windows"
  27. }
  28. // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
  29. func Logger() macaron.Handler {
  30. return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
  31. start := time.Now()
  32. rw := res.(macaron.ResponseWriter)
  33. c.Next()
  34. content := fmt.Sprintf("Completed %s %v %s in %v", req.URL.Path, rw.Status(), http.StatusText(rw.Status()), time.Since(start))
  35. if !isWindows {
  36. switch rw.Status() {
  37. case 200:
  38. content = fmt.Sprintf("\033[1;32m%s\033[0m", content)
  39. case 304:
  40. return
  41. content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
  42. case 404:
  43. content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
  44. case 500:
  45. content = fmt.Sprintf("\033[1;36m%s\033[0m", content)
  46. }
  47. }
  48. log.Info(content)
  49. }
  50. }