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.

73 lines
2.2 KiB

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