Skip to content

Commit

Permalink
Fix LogRequest Middleware (#35)
Browse files Browse the repository at this point in the history
* fix logger info status and move correlation middleware and getLoggerFromContext from api-server

* fix lint issue

* resolve

* resolve

* resolve

* add errors in getlogger

* fix error invalid key-value pairs

* fix error check

* fixed context keys string

* revert

* Fix LogRequest middleware

* if context looger doesn't exist

* remove global variable
  • Loading branch information
0xmuralik authored Feb 25, 2022
1 parent 02df8af commit fe7885c
Showing 1 changed file with 30 additions and 25 deletions.
55 changes: 30 additions & 25 deletions logging/rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit fe7885c

Please sign in to comment.