-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: create a logrus-gin middleware
- Loading branch information
1 parent
de8b095
commit af29513
Showing
3 changed files
with
41 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package middleware | ||
|
||
import ( | ||
"github.com/gin-gonic/gin" | ||
"github.com/sirupsen/logrus" | ||
"time" | ||
) | ||
|
||
func LogrusMiddleware(logger *logrus.Logger) gin.HandlerFunc { | ||
return func(c *gin.Context) { | ||
startTime := time.Now() | ||
c.Next() | ||
endTime := time.Now() | ||
latency := endTime.Sub(startTime) | ||
|
||
statusCode := c.Writer.Status() | ||
clientIP := c.ClientIP() | ||
method := c.Request.Method | ||
path := c.Request.URL.Path | ||
|
||
errors := c.Errors.ByType(gin.ErrorTypePrivate).String() | ||
|
||
entry := logger.WithFields(logrus.Fields{ | ||
"status_code": statusCode, | ||
"latency": latency, | ||
"client_ip": clientIP, | ||
"method": method, | ||
"path": path, | ||
"errors": errors, | ||
}) | ||
|
||
if len(errors) > 0 { | ||
entry.Error(errors) | ||
} else { | ||
entry.Info() | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters