refactor: a better DI-friendy logger implementation that doesn't suck

This commit is contained in:
2025-06-23 14:18:25 +03:00
parent ea3743cb04
commit 1b55498b00
3 changed files with 35 additions and 29 deletions

View File

@@ -20,6 +20,7 @@ import (
"github.com/gin-gonic/gin"
"go.uber.org/fx"
"go.uber.org/zap"
"easywish/config"
docs "easywish/docs"
@@ -42,6 +43,7 @@ func main() {
fx.New(
fx.Provide(
logger.NewLogger,
logger.NewSyncLogger,
gin.Default,
),
database.Module,
@@ -49,7 +51,7 @@ func main() {
controllers.Module,
routes.Module,
fx.Invoke(func(lc fx.Lifecycle, router *gin.Engine) {
fx.Invoke(func(lc fx.Lifecycle, router *gin.Engine, syncLogger *logger.SyncLogger) {
// Swagger
docs.SwaggerInfo.Schemes = []string{"http"}
@@ -65,6 +67,7 @@ func main() {
OnStart: func(ctx context.Context) error {
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
syncLogger.Fatal("Server failed", zap.Error(err))
}
}()
return nil
@@ -72,7 +75,15 @@ func main() {
OnStop: func(ctx context.Context) error {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return server.Shutdown(shutdownCtx)
if err := server.Shutdown(shutdownCtx); err != nil {
syncLogger.Error("Server shutdown error", zap.Error(err))
}
if err := syncLogger.Close(); err != nil {
syncLogger.Error("Logger sync error", zap.Error(err))
}
return nil
},
})
}),