You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

logger.go 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 (
  24. ColorLog = true
  25. LogTimeFormat = "2006-01-02 15:04:05"
  26. )
  27. func init() {
  28. ColorLog = runtime.GOOS != "windows"
  29. }
  30. // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
  31. func Logger() Handler {
  32. return func(ctx *Context, log *log.Logger) {
  33. start := time.Now()
  34. log.Printf("%s: Started %s %s for %s", time.Now().Format(LogTimeFormat), ctx.Req.Method, ctx.Req.RequestURI, ctx.RemoteAddr())
  35. rw := ctx.Resp.(ResponseWriter)
  36. ctx.Next()
  37. content := fmt.Sprintf("%s: Completed %s %v %s in %v", time.Now().Format(LogTimeFormat), ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start))
  38. if ColorLog {
  39. switch rw.Status() {
  40. case 200, 201, 202:
  41. content = fmt.Sprintf("\033[1;32m%s\033[0m", content)
  42. case 301, 302:
  43. content = fmt.Sprintf("\033[1;37m%s\033[0m", content)
  44. case 304:
  45. content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
  46. case 401, 403:
  47. content = fmt.Sprintf("\033[4;31m%s\033[0m", content)
  48. case 404:
  49. content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
  50. case 500:
  51. content = fmt.Sprintf("\033[1;36m%s\033[0m", content)
  52. }
  53. }
  54. log.Println(content)
  55. }
  56. }