logger.go 3.7 KB

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