Some checks failed
CI Pipeline / Lint (push) Failing after 5m12s
CI Pipeline / Test (push) Has been skipped
CI Pipeline / Security Scan (push) Successful in 6m3s
CI Pipeline / Build (push) Has been skipped
CI Pipeline / Security Scan (pull_request) Successful in 2m36s
CI Pipeline / Notification (push) Successful in 2s
CI Pipeline / Lint (pull_request) Failing after 2m38s
CI Pipeline / Test (pull_request) Has been skipped
CI Pipeline / Build (pull_request) Has been skipped
CI Pipeline / Notification (pull_request) Successful in 1s
56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"time"
|
|
)
|
|
|
|
// Logger là một middleware đơn giản để ghi log các request
|
|
func Logger() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// Ghi thời gian bắt đầu xử lý request
|
|
start := time.Now()
|
|
|
|
// Xử lý request
|
|
c.Next()
|
|
|
|
// Tính thời gian xử lý
|
|
latency := time.Since(start)
|
|
|
|
|
|
// Lấy thông tin response
|
|
status := c.Writer.Status()
|
|
method := c.Request.Method
|
|
path := c.Request.URL.Path
|
|
|
|
// Ghi log
|
|
if status >= 400 {
|
|
// Log lỗi
|
|
// Ở đây bạn có thể sử dụng logger của dự án thay vì in ra console
|
|
// Ví dụ: logger.Error("Request failed", "method", method, "path", path, "status", status, "latency", latency)
|
|
gin.DefaultErrorWriter.Write([]byte(
|
|
"[GIN] " + time.Now().Format("2006/01/02 - 15:04:05") +
|
|
" | " + method +
|
|
" | " + path +
|
|
" | " + latency.String() +
|
|
" | " + c.ClientIP() +
|
|
" | " + c.Request.UserAgent() +
|
|
" | " + c.Errors.ByType(gin.ErrorTypePrivate).String() +
|
|
"\n",
|
|
))
|
|
} else {
|
|
// Log thông thường
|
|
// Ví dụ: logger.Info("Request processed", "method", method, "path", path, "status", status, "latency", latency)
|
|
gin.DefaultWriter.Write([]byte(
|
|
"[GIN] " + time.Now().Format("2006/01/02 - 15:04:05") +
|
|
" | " + method +
|
|
" | " + path +
|
|
" | " + latency.String() +
|
|
" | " + c.ClientIP() +
|
|
" | " + c.Request.UserAgent() +
|
|
"\n",
|
|
))
|
|
}
|
|
}
|
|
}
|