Skip to content

Commit

Permalink
feat: fix request_id (#33) (#34)
Browse files Browse the repository at this point in the history
* feat:  request_id &  slow sql logger
  • Loading branch information
Han-Ya-Jun authored Jul 29, 2024
1 parent 6d1d32e commit 9b06c09
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/bkauth/pkg/database/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func logSlowSQL(start time.Time, query string, args interface{}) {

// current, set 20ms
if latency > 20 {
logger.Debug(
logger.Error(
"-",
zap.String("sql", strings.ReplaceAll(query, "\n\t\t", " ")),
zap.String("sql", truncateArgs(args, ArgsTruncateLength)),
Expand Down
2 changes: 1 addition & 1 deletion src/bkauth/pkg/middleware/request_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func RequestID() gin.HandlerFunc {
zap.S().Debug("Middleware: RequestID")

requestID := c.GetHeader(util.RequestIDHeaderKey)
if requestID == "" || len(requestID) != 32 {
if requestID == "" {
requestID = hex.EncodeToString(uuid.Must(uuid.NewV4()).Bytes())
}
util.SetRequestID(c, requestID)
Expand Down
21 changes: 20 additions & 1 deletion src/bkauth/pkg/server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,17 @@
package server

import (
"fmt"
"time"

"github.com/gin-gonic/gin"

"bkauth/pkg/api/app"
"bkauth/pkg/api/basic"
"bkauth/pkg/api/oauth"
"bkauth/pkg/config"
"bkauth/pkg/middleware"
"bkauth/pkg/util"
)

// NewRouter ...
Expand All @@ -39,7 +43,7 @@ func NewRouter(cfg *config.Config) *gin.Engine {
// router := gin.Default()
router := gin.New()
// MW: gin default logger
router.Use(gin.Logger())
router.Use(gin.LoggerWithFormatter(ginLogFormat))
// MW: recovery with sentry
router.Use(middleware.Recovery(cfg.Sentry.Enable))
// MW: request_id
Expand All @@ -65,3 +69,18 @@ func NewRouter(cfg *config.Config) *gin.Engine {

return router
}
func ginLogFormat(param gin.LogFormatterParams) string {
// your custom format
return fmt.Sprintf("%s - [%s] \"%s %s %s %s %d \"%s\" %s %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC1123),
param.Method,
param.Path,
param.Request.Proto,
param.Request.Header.Get(util.RequestIDHeaderKey),
param.StatusCode,
param.Latency,
param.Request.UserAgent(),
param.ErrorMessage,
)
}

0 comments on commit 9b06c09

Please sign in to comment.