logger.go 1.6 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. "fmt"
  18. "net/http"
  19. "runtime"
  20. "time"
  21. "github.com/Unknwon/macaron"
  22. "github.com/grafana/grafana/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. return
  40. case 304:
  41. //content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
  42. return
  43. case 404:
  44. content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
  45. case 500:
  46. content = fmt.Sprintf("\033[1;36m%s\033[0m", content)
  47. }
  48. }
  49. log.Info(content)
  50. }
  51. }