mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2026-01-16 12:22:30 +00:00
* Refactor logging to use centralized logger utility - Removed direct usage of zerolog in multiple files and replaced it with a centralized logging utility in the `utils` package. - Introduced `Loggers` struct to manage different loggers (Audit, HTTP, App) with configurable levels and outputs. - Updated all relevant files to utilize the new logging structure, ensuring consistent logging practices across the application. - Enhanced error handling and logging messages for better traceability and debugging. * refactor: update logging implementation to use new logger structure * Refactor logging to use tlog package - Replaced instances of utils logging with tlog in various controllers, services, and middleware. - Introduced audit logging for login success, login failure, and logout events. - Created tlog package with structured logging capabilities using zerolog. - Added tests for the new tlog logger functionality. * refactor: update logging configuration in environment files * fix: adding coderabbit suggestions * fix: ensure correct audit caller * fix: include reason in audit login failure logs
73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/steveiliop56/tinyauth/internal/utils/tlog"
|
|
)
|
|
|
|
var (
|
|
loggerSkipPathsPrefix = []string{
|
|
"GET /api/health",
|
|
"HEAD /api/health",
|
|
"GET /favicon.ico",
|
|
}
|
|
)
|
|
|
|
type ZerologMiddleware struct{}
|
|
|
|
func NewZerologMiddleware() *ZerologMiddleware {
|
|
return &ZerologMiddleware{}
|
|
}
|
|
|
|
func (m *ZerologMiddleware) Init() error {
|
|
return nil
|
|
}
|
|
|
|
func (m *ZerologMiddleware) logPath(path string) bool {
|
|
for _, prefix := range loggerSkipPathsPrefix {
|
|
if strings.HasPrefix(path, prefix) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (m *ZerologMiddleware) Middleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
tStart := time.Now()
|
|
|
|
c.Next()
|
|
|
|
code := c.Writer.Status()
|
|
address := c.Request.RemoteAddr
|
|
clientIP := c.ClientIP()
|
|
method := c.Request.Method
|
|
path := c.Request.URL.Path
|
|
|
|
latency := time.Since(tStart).String()
|
|
|
|
subLogger := tlog.HTTP.With().Str("method", method).
|
|
Str("path", path).
|
|
Str("address", address).
|
|
Str("client_ip", clientIP).
|
|
Int("status", code).
|
|
Str("latency", latency).Logger()
|
|
|
|
if m.logPath(method + " " + path) {
|
|
switch {
|
|
case code >= 400 && code < 500:
|
|
subLogger.Warn().Msg("Client Error")
|
|
case code >= 500:
|
|
subLogger.Error().Msg("Server Error")
|
|
default:
|
|
subLogger.Info().Msg("Request")
|
|
}
|
|
} else {
|
|
subLogger.Debug().Msg("Request")
|
|
}
|
|
}
|
|
}
|