logger.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 The Macaron Authors
  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 macaron
  16. import (
  17. "fmt"
  18. "log"
  19. "net/http"
  20. "runtime"
  21. "time"
  22. )
  23. var ColorLog = true
  24. func init() {
  25. ColorLog = runtime.GOOS != "windows"
  26. }
  27. // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
  28. func Logger() Handler {
  29. return func(ctx *Context, log *log.Logger) {
  30. start := time.Now()
  31. log.Printf("Started %s %s for %s", ctx.Req.Method, ctx.Req.RequestURI, ctx.RemoteAddr())
  32. rw := ctx.Resp.(ResponseWriter)
  33. ctx.Next()
  34. content := fmt.Sprintf("Completed %s %v %s in %v", ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start))
  35. if ColorLog {
  36. switch rw.Status() {
  37. case 200, 201, 202:
  38. content = fmt.Sprintf("\033[1;32m%s\033[0m", content)
  39. case 301, 302:
  40. content = fmt.Sprintf("\033[1;37m%s\033[0m", content)
  41. case 304:
  42. content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
  43. case 401, 403:
  44. content = fmt.Sprintf("\033[4;31m%s\033[0m", content)
  45. case 404:
  46. content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
  47. case 500:
  48. content = fmt.Sprintf("\033[1;36m%s\033[0m", content)
  49. }
  50. }
  51. log.Println(content)
  52. }
  53. }