logger.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // Package logger provides request logging via middleware. See _examples/http_request/request-logger
  2. package logger
  3. import (
  4. "fmt"
  5. "strconv"
  6. "time"
  7. "github.com/kataras/iris/context"
  8. "github.com/ryanuber/columnize"
  9. )
  10. type requestLoggerMiddleware struct {
  11. config Config
  12. }
  13. // New creates and returns a new request logger middleware.
  14. // Do not confuse it with the framework's Logger.
  15. // This is for the http requests.
  16. //
  17. // Receives an optional configuation.
  18. func New(cfg ...Config) context.Handler {
  19. c := DefaultConfig()
  20. if len(cfg) > 0 {
  21. c = cfg[0]
  22. }
  23. c.buildSkipper()
  24. l := &requestLoggerMiddleware{config: c}
  25. return l.ServeHTTP
  26. }
  27. // Serve serves the middleware
  28. func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) {
  29. // skip logs and serve the main request immediately
  30. if l.config.skip != nil {
  31. if l.config.skip(ctx) {
  32. ctx.Next()
  33. return
  34. }
  35. }
  36. //all except latency to string
  37. var status, ip, method, path string
  38. var latency time.Duration
  39. var startTime, endTime time.Time
  40. startTime = time.Now()
  41. ctx.Next()
  42. //no time.Since in order to format it well after
  43. endTime = time.Now()
  44. latency = endTime.Sub(startTime)
  45. if l.config.Status {
  46. status = strconv.Itoa(ctx.GetStatusCode())
  47. }
  48. if l.config.IP {
  49. ip = ctx.RemoteAddr()
  50. }
  51. if l.config.Method {
  52. method = ctx.Method()
  53. }
  54. if l.config.Path {
  55. if l.config.Query {
  56. path = ctx.Request().URL.RequestURI()
  57. } else {
  58. path = ctx.Path()
  59. }
  60. }
  61. var message interface{}
  62. if ctxKeys := l.config.MessageContextKeys; len(ctxKeys) > 0 {
  63. for _, key := range ctxKeys {
  64. msg := ctx.Values().Get(key)
  65. if message == nil {
  66. message = msg
  67. } else {
  68. message = fmt.Sprintf(" %v %v", message, msg)
  69. }
  70. }
  71. }
  72. var headerMessage interface{}
  73. if headerKeys := l.config.MessageHeaderKeys; len(headerKeys) > 0 {
  74. for _, key := range headerKeys {
  75. msg := ctx.GetHeader(key)
  76. if headerMessage == nil {
  77. headerMessage = msg
  78. } else {
  79. headerMessage = fmt.Sprintf(" %v %v", headerMessage, msg)
  80. }
  81. }
  82. }
  83. // print the logs
  84. if logFunc := l.config.LogFunc; logFunc != nil {
  85. logFunc(endTime, latency, status, ip, method, path, message, headerMessage)
  86. return
  87. }
  88. if l.config.Columns {
  89. endTimeFormatted := endTime.Format("2006/01/02 - 15:04:05")
  90. output := Columnize(endTimeFormatted, latency, status, ip, method, path, message, headerMessage)
  91. ctx.Application().Logger().Printer.Output.Write([]byte(output))
  92. return
  93. }
  94. // no new line, the framework's logger is responsible how to render each log.
  95. line := fmt.Sprintf("%v %4v %s %s %s", status, latency, ip, method, path)
  96. if message != nil {
  97. line += fmt.Sprintf(" %v", message)
  98. }
  99. if headerMessage != nil {
  100. line += fmt.Sprintf(" %v", headerMessage)
  101. }
  102. ctx.Application().Logger().Info(line)
  103. }
  104. // Columnize formats the given arguments as columns and returns the formatted output,
  105. // note that it appends a new line to the end.
  106. func Columnize(nowFormatted string, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) string {
  107. titles := "Time | Status | Latency | IP | Method | Path"
  108. line := fmt.Sprintf("%s | %v | %4v | %s | %s | %s", nowFormatted, status, latency, ip, method, path)
  109. if message != nil {
  110. titles += " | Message"
  111. line += fmt.Sprintf(" | %v", message)
  112. }
  113. if headerMessage != nil {
  114. titles += " | HeaderMessage"
  115. line += fmt.Sprintf(" | %v", headerMessage)
  116. }
  117. outputC := []string{
  118. titles,
  119. line,
  120. }
  121. output := columnize.SimpleFormat(outputC) + "\n"
  122. return output
  123. }