Skip to content

Instantly share code, notes, and snippets.

@tyzbit
Last active May 3, 2022 23:58
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 tyzbit/f335db5d3bd97c4db4e2a67892700000 to your computer and use it in GitHub Desktop.
Save tyzbit/f335db5d3bd97c4db4e2a67892700000 to your computer and use it in GitHub Desktop.
Gin JSON Formatter
func GinJSONFormatter(param gin.LogFormatterParams) string {
jsonFormat := `{"time":"%s","clientip":"%s","method":"%s","uri":"%s","status":%3d,"latency":"%v","message":"%s","host":"%s","useragent":"%s","proto":"%s","error_msg":"%s","size":%d}` + "\n"
return fmt.Sprintf(jsonFormat,
param.TimeStamp.Format(TimeFormatter),
param.ClientIP,
param.Method,
param.Request.RequestURI,
param.StatusCode,
param.Latency,
fmt.Sprintf("%s %s %s", param.Method, param.Request.URL, param.Request.Proto),
param.Request.Host,
param.Request.UserAgent(),
param.Request.Proto,
param.ErrorMessage,
param.BodySize,
)
}
@tyzbit
Copy link
Author

tyzbit commented May 3, 2022

Usage:

r := gin.New()
r.Use(gin.LoggerWithFormatter(GinJSONFormatter))

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