Changeset 0.33.0 (#207)
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit is contained in:
@@ -1,130 +1,112 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RequestLoggerConfig holds the configuration for the request logger
|
||||
// RequestLoggerConfig holds the configuration for the request logger.
|
||||
type RequestLoggerConfig struct {
|
||||
SkipPaths []string
|
||||
Logger *log.Logger
|
||||
TimeFormat string
|
||||
TimeZone string
|
||||
SkipPaths []string
|
||||
}
|
||||
|
||||
// DefaultRequestLoggerConfig returns the default request logger configuration
|
||||
// DefaultRequestLoggerConfig returns the default request logger configuration.
|
||||
func DefaultRequestLoggerConfig() *RequestLoggerConfig {
|
||||
return &RequestLoggerConfig{
|
||||
SkipPaths: []string{"/health", "/ready", "/metrics"},
|
||||
Logger: log.Default(),
|
||||
TimeFormat: "2006/01/02 - 15:04:05",
|
||||
TimeZone: "UTC",
|
||||
SkipPaths: []string{"/health", "/ready", "/metrics"},
|
||||
}
|
||||
}
|
||||
|
||||
// Logger returns a Gin middleware handler for logging requests
|
||||
// Logger returns a Gin middleware handler for logging requests.
|
||||
func Logger() gin.HandlerFunc {
|
||||
return LoggerWithConfig(DefaultRequestLoggerConfig())
|
||||
}
|
||||
|
||||
// LoggerWithConfig returns a Gin middleware handler for logging requests with custom configuration
|
||||
// LoggerWithConfig returns a Gin middleware handler for structured
|
||||
// request logging via slog. When LOG_FORMAT=json the output is
|
||||
// machine-parseable JSON lines; otherwise human-readable key=value.
|
||||
func LoggerWithConfig(config *RequestLoggerConfig) gin.HandlerFunc {
|
||||
skip := make(map[string]bool, len(config.SkipPaths))
|
||||
for _, p := range config.SkipPaths {
|
||||
skip[p] = true
|
||||
}
|
||||
|
||||
return func(c *gin.Context) {
|
||||
// Skip logging for certain paths
|
||||
path := c.Request.URL.Path
|
||||
skip := false
|
||||
for _, skipPath := range config.SkipPaths {
|
||||
if path == skipPath {
|
||||
skip = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
raw := c.Request.URL.RawQuery
|
||||
|
||||
c.Next()
|
||||
|
||||
if skip {
|
||||
if skip[path] {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Calculate latency
|
||||
latency := time.Since(start)
|
||||
|
||||
// Get the client IP
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
// Get the request method
|
||||
method := c.Request.Method
|
||||
|
||||
// Get the status code
|
||||
statusCode := c.Writer.Status()
|
||||
|
||||
// Log the request
|
||||
if raw != "" {
|
||||
raw = "?" + raw
|
||||
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
|
||||
reqID, _ := c.Get(RequestIDKey)
|
||||
|
||||
attrs := []any{
|
||||
"method", c.Request.Method,
|
||||
"path", path,
|
||||
"status", c.Writer.Status(),
|
||||
"latency_ms", time.Since(start).Milliseconds(),
|
||||
"client_ip", c.ClientIP(),
|
||||
}
|
||||
|
||||
config.Logger.Printf(
|
||||
"[%s] %s %s%s | %d | %v | %s",
|
||||
clientIP,
|
||||
method,
|
||||
path,
|
||||
raw,
|
||||
statusCode,
|
||||
latency,
|
||||
c.Errors.ByType(gin.ErrorTypePrivate).String(),
|
||||
)
|
||||
if id, ok := reqID.(string); ok && id != "" {
|
||||
attrs = append(attrs, "request_id", id)
|
||||
}
|
||||
if uid := c.GetString("user_id"); uid != "" {
|
||||
attrs = append(attrs, "user_id", uid)
|
||||
}
|
||||
if errs := c.Errors.ByType(gin.ErrorTypePrivate).String(); errs != "" {
|
||||
attrs = append(attrs, "errors", errs)
|
||||
}
|
||||
|
||||
slog.Info("request", attrs...)
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery returns a Gin middleware handler for recovering from panics
|
||||
// Recovery returns a Gin middleware handler for recovering from panics.
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return RecoveryWithConfig(DefaultRecoveryConfig())
|
||||
}
|
||||
|
||||
// RecoveryConfig holds the configuration for the recovery middleware
|
||||
// RecoveryConfig holds the configuration for the recovery middleware.
|
||||
type RecoveryConfig struct {
|
||||
Logger *log.Logger
|
||||
TimeFormat string
|
||||
TimeZone string
|
||||
SkipStackTrace bool
|
||||
StackTraceSize int
|
||||
StackAll bool
|
||||
}
|
||||
|
||||
// DefaultRecoveryConfig returns the default recovery configuration
|
||||
// DefaultRecoveryConfig returns the default recovery configuration.
|
||||
func DefaultRecoveryConfig() *RecoveryConfig {
|
||||
return &RecoveryConfig{
|
||||
Logger: log.Default(),
|
||||
TimeFormat: "2006/01/02 - 15:04:05",
|
||||
TimeZone: "UTC",
|
||||
SkipStackTrace: false,
|
||||
StackTraceSize: 1024,
|
||||
StackAll: false,
|
||||
}
|
||||
}
|
||||
|
||||
// RecoveryWithConfig returns a Gin middleware handler for recovering from panics with custom configuration
|
||||
// RecoveryWithConfig returns a Gin middleware handler for recovering
|
||||
// from panics with custom configuration.
|
||||
func RecoveryWithConfig(config *RecoveryConfig) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// Log the panic
|
||||
config.Logger.Printf("[PANIC] %v", err)
|
||||
|
||||
// Abort with a 500 error
|
||||
reqID, _ := c.Get(RequestIDKey)
|
||||
slog.Error("panic",
|
||||
"error", err,
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"request_id", reqID,
|
||||
)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "internal server error",
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user