modified: go.mod

modified:   go.sum
	new file:   internal/logger/interface.go
	new file:   internal/logger/route_logger.go
	modified:   internal/router/router.go
add router logger that logg all router in the start api_yal
This commit is contained in:
2026-03-03 15:26:29 +05:00
parent 9a3ff9ad3d
commit f25dfeacb8
5 changed files with 188 additions and 4 deletions
+1
View File
@@ -16,6 +16,7 @@ require (
require (
github.com/go-chi/chi v1.5.5
github.com/go-chi/chi/v5 v5.2.5
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/joho/godotenv v1.5.1
+2
View File
@@ -1,6 +1,8 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw=
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -0,0 +1,75 @@
// pkg/logger/interface.go
package logger
import "go.uber.org/zap"
// LoggerInterface определяет контракт для логгера
type LoggerInterface interface {
Debug(msg string, fields ...zap.Field)
Info(msg string, fields ...zap.Field)
Warn(msg string, fields ...zap.Field)
Error(msg string, fields ...zap.Field)
Fatal(msg string, fields ...zap.Field)
Debugf(template string, args ...interface{})
Infof(template string, args ...interface{})
Warnf(template string, args ...interface{})
Errorf(template string, args ...interface{})
Fatalf(template string, args ...interface{})
With(fields ...zap.Field) LoggerInterface
}
// wrapper обертка для zap.Logger
type wrapper struct {
logger *zap.Logger
}
// NewWrapper создает новую обертку
func NewWrapper(logger *zap.Logger) LoggerInterface {
return &wrapper{logger: logger}
}
func (w *wrapper) Debug(msg string, fields ...zap.Field) {
w.logger.Debug(msg, fields...)
}
func (w *wrapper) Info(msg string, fields ...zap.Field) {
w.logger.Info(msg, fields...)
}
func (w *wrapper) Warn(msg string, fields ...zap.Field) {
w.logger.Warn(msg, fields...)
}
func (w *wrapper) Error(msg string, fields ...zap.Field) {
w.logger.Error(msg, fields...)
}
func (w *wrapper) Fatal(msg string, fields ...zap.Field) {
w.logger.Fatal(msg, fields...)
}
func (w *wrapper) Debugf(template string, args ...interface{}) {
w.logger.Sugar().Debugf(template, args...)
}
func (w *wrapper) Infof(template string, args ...interface{}) {
w.logger.Sugar().Infof(template, args...)
}
func (w *wrapper) Warnf(template string, args ...interface{}) {
w.logger.Sugar().Warnf(template, args...)
}
func (w *wrapper) Errorf(template string, args ...interface{}) {
w.logger.Sugar().Errorf(template, args...)
}
func (w *wrapper) Fatalf(template string, args ...interface{}) {
w.logger.Sugar().Fatalf(template, args...)
}
func (w *wrapper) With(fields ...zap.Field) LoggerInterface {
return &wrapper{logger: w.logger.With(fields...)}
}
@@ -0,0 +1,100 @@
package logger
import (
"net/http"
"sort"
"strings"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
type RouteLogger struct {
logger LoggerInterface
}
func NewRouteLogger(log LoggerInterface) *RouteLogger {
return &RouteLogger{
logger: log,
}
}
func (rl *RouteLogger) LogRoutes(router *chi.Mux) {
routes := rl.extractRoutes(router)
rl.printFormattedRoutes(routes)
}
func (rl *RouteLogger) extractRoutes(router *chi.Mux) []RouteInfo {
var routes []RouteInfo
walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
if route != "" {
routes = append(routes, RouteInfo{
Method: method,
Path: route,
})
}
return nil
}
if err := chi.Walk(router, walkFunc); err != nil {
rl.logger.Error("Failed to walk routes", zap.Error(err))
}
return routes
}
func (rl *RouteLogger) printFormattedRoutes(routes []RouteInfo) {
if len(routes) == 0 {
rl.logger.Info("No routes found")
return
}
// Группируем по пути
routesByPath := make(map[string][]string)
for _, route := range routes {
routesByPath[route.Path] = append(routesByPath[route.Path], route.Method)
}
// Сортируем пути
var paths []string
for path := range routesByPath {
paths = append(paths, path)
}
sort.Strings(paths)
rl.logger.Info("📋 Registered API Routes:")
rl.logger.Info("┌──────────────────────────────────────────────────────────────┐")
for _, path := range paths {
methods := routesByPath[path]
sort.Strings(methods)
methodsStr := strings.Join(methods, ", ")
if len(methodsStr) > 12 {
methodsStr = methodsStr[:9] + "..."
}
methodField := methodsStr
if len(methodField) < 12 {
methodField = methodField + strings.Repeat(" ", 12-len(methodField))
}
pathField := path
if len(pathField) > 45 {
pathField = pathField[:42] + "..."
} else {
pathField = pathField + strings.Repeat(" ", 45-len(pathField))
}
rl.logger.Info("│ " + methodField + " " + pathField + " │")
}
rl.logger.Info("└──────────────────────────────────────────────────────────────┘")
rl.logger.Info("Total routes registered: %d", zap.Int("count", len(routes)))
}
type RouteInfo struct {
Method string
Path string
}
@@ -4,10 +4,9 @@ import (
"api_yal/internal/config"
"api_yal/internal/logger"
"encoding/json"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/v5"
"gorm.io/gorm"
"net/http"
)
func SetupRouter(db *gorm.DB, config *config.Config) http.Handler {
@@ -19,8 +18,15 @@ func SetupRouter(db *gorm.DB, config *config.Config) http.Handler {
// Health check
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "healthy"})
})
zapLogger.Info("End setup routers")
// Логируем все зарегистрированные маршруты
routeLogger := logger.NewRouteLogger(logger.NewWrapper(zapLogger))
routeLogger.LogRoutes(r)
return r
}