From 3b0d2b270f414a74123ccb7a36773617c605dc72 Mon Sep 17 00:00:00 2001 From: Roman Serikov Date: Mon, 1 Mar 2021 21:07:13 +0300 Subject: [PATCH] Removed ts from gin logger in production --- cmd/api/main.go | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/cmd/api/main.go b/cmd/api/main.go index f20ac504c..cd3a5c215 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -1,6 +1,8 @@ package main import ( + "fmt" + "os" "strings" "time" @@ -69,7 +71,8 @@ func newApp() *app { } func (api *app) makeRouter() { - r := gin.Default() + r := gin.New() + r.MaxMultipartMemory = 4 << 20 // max upload size 4 MiB if v, ok := binding.Validator.Engine().(*validator.Validate); ok { @@ -86,6 +89,14 @@ func (api *app) makeRouter() { r.Use(helpers.SentryMiddleware()) } + r.Use(gin.Recovery()) + + if env := os.Getenv(config.EnvironmentVar); env == config.EnvironmentProd { + r.Use(loggerFormat()) + } else { + r.Use(gin.Logger()) + } + v1 := r.Group("v1") { v1.GET("swagger.json", api.Context.GetSwaggerDoc) @@ -288,8 +299,22 @@ func corsSettings() gin.HandlerFunc { return cors.New(cors.Config{ AllowOrigins: []string{"*"}, AllowMethods: []string{"GET", "POST", "PATCH"}, - AllowHeaders: []string{"X-Requested-With", "Authorization", "Origin", "Content-Length", "Content-Type", "Referer", "Cache-Control"}, + AllowHeaders: []string{"X-Requested-With", "Authorization", "Origin", "Content-Length", "Content-Type", "Referer", "Cache-Control", "User-Agent"}, AllowCredentials: true, MaxAge: 12 * time.Hour, }) } + +func loggerFormat() gin.HandlerFunc { + return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { + return fmt.Sprintf("%15s | %3d | %13v | %-7s %s | %s\n%s", + param.ClientIP, + param.StatusCode, + param.Latency, + param.Method, + param.Path, + param.Request.UserAgent(), + param.ErrorMessage, + ) + }) +}