Skip to content

Instantly share code, notes, and snippets.

@tiagopotencia
Created January 26, 2018 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagopotencia/89b1536690943511dccf8e2c447eeee5 to your computer and use it in GitHub Desktop.
Save tiagopotencia/89b1536690943511dccf8e2c447eeee5 to your computer and use it in GitHub Desktop.
HttpLoggerMiddleware
package httplogger
import (
"github.com/gin-gonic/gin"
"time"
"fmt"
"log"
)
func LogRequestInfo(notlogged ...string) gin.HandlerFunc {
var skip map[string]struct{}
if length := len(notlogged); length > 0 {
skip = make(map[string]struct{}, length)
for _, path := range notlogged {
skip[path] = struct{}{}
}
}
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
// Process request
c.Next()
// Log only when path is not being skipped
if _, ok := skip[path]; !ok {
// Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
if raw != "" {
path = path + "?" + raw
}
logSeverity := "Info"
if statusCode > 399 {
logSeverity = "Error"
}
log.Println(fmt.Sprintf("%s: %s to: %s | Code: %3d | In: %v | By: %s",
logSeverity,
method,
path,
statusCode,
latency,
clientIP,
), nil)
}
}
}
@tiagopotencia
Copy link
Author

This httplogger is based on Gin webframework (https://github.com/gin-gonic/gin)

To use this middleware on your api, you just need to use this middleware with

        engine := gin.New()
	engine.Use(gin.Recovery())

	port := os.Getenv("PORT")

	if port == "" {
		port = "8080"
	}

	engine.Use(httplogger.LogRequestInfo())
        err := engine.Run(":" + port)
        if err != nil {
		log.Println(err.Error())
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment