diff --git a/logging/rest.go b/logging/rest.go index 51d7f09..f9c490d 100644 --- a/logging/rest.go +++ b/logging/rest.go @@ -8,32 +8,37 @@ import ( "go.uber.org/zap" ) -var l *zap.Logger - // LogRequest is a gin middleware that logs useful informations on each request as they come. -func LogRequest(logger *zap.Logger) gin.HandlerFunc { - l = logger - return log -} - -func log(c *gin.Context) { - start := time.Now() - - c.Next() - - // some evil middlewares modify this values - path := c.Request.URL.Path - query := c.Request.URL.RawQuery - - l.Info(path, - zap.Int("status", c.Writer.Status()), - zap.String("method", c.Request.Method), - zap.String("path", path), - zap.String("query", query), - zap.String("ip", c.ClientIP()), - zap.String("user-agent", c.Request.UserAgent()), - zap.String("time", start.Format(time.RFC3339)), - ) +func LogRequest(fallBackLogger *zap.Logger) gin.HandlerFunc { + return func(c *gin.Context) { + logger := fallBackLogger + + ctxLogger, err := GetLoggerFromContext(c) + if err != nil && logger == nil { + panic(fmt.Errorf("Can't get logger from context error:%w", err)) + } + if ctxLogger != nil { + logger = ctxLogger.Desugar() + } + + start := time.Now() + + c.Next() + + // some evil middlewares modify this values + path := c.Request.URL.Path + query := c.Request.URL.RawQuery + + logger.Info(path, + zap.Int("status", c.Writer.Status()), + zap.String("method", c.Request.Method), + zap.String("path", path), + zap.String("query", query), + zap.String("ip", c.ClientIP()), + zap.String("user-agent", c.Request.UserAgent()), + zap.String("time", start.Format(time.RFC3339)), + ) + } } func GetLoggerFromContext(c *gin.Context) (*zap.SugaredLogger, error) {