github.com/tcotav/boggle@v0.0.0-20231023231124-a86497006536/middleware/logging.go (about)

     1  package middleware
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/gin-gonic/gin"
     7  
     8  	"github.com/rs/zerolog"
     9  	"github.com/rs/zerolog/log"
    10  )
    11  
    12  func init() {
    13  	// TODO set the global log level to info -- probably better sent in via config than h/coded
    14  	zerolog.SetGlobalLevel(zerolog.InfoLevel)
    15  }
    16  
    17  // RequestLogger is a gin middleware that logs requests in json format and prints out pretty standard http access logs
    18  func RequestLogger() gin.HandlerFunc {
    19  	return func(c *gin.Context) {
    20  		client_ip := c.ClientIP()
    21  		user_agent := c.Request.UserAgent()
    22  		method := c.Request.Method
    23  		path := c.Request.URL.Path
    24  
    25  		t := time.Now()
    26  		c.Next() // this hands off to the next handler in the chain
    27  		latency := float32(time.Since(t).Seconds())
    28  		status := c.Writer.Status()
    29  
    30  		log.Info().Str("client_ip", client_ip).Str("user_agent", user_agent).Str("method", method).Str("path", path).Float32("latency", latency).Int("status", status).Msg("")
    31  	}
    32  }