Implement comprehensive graceful shutdown with JSON logging

- Added signal.NotifyContext for modern signal handling in cmd/server/main.go
- Implemented BaseContext for proper context propagation to HTTP handlers
- Added readiness drain delay before shutdown for graceful degradation
- Fixed PID detection in start-server.sh to target actual server process
- Added Logging.JSON configuration option with DLC_LOGGING_JSON environment variable
- Created comprehensive test script that validates entire server lifecycle
- Updated documentation with JSON logging configuration examples
- All shutdown logs now appear correctly in JSON format
- Server terminates gracefully on SIGTERM with proper log flushing

The graceful shutdown implementation follows VictoriaMetrics best practices:
1. Catches termination signals (SIGTERM, SIGINT)
2. Stops accepting new requests but allows ongoing requests to complete
3. Waits for active requests to finish within configured timeout
4. Releases resources and performs cleanup
5. Logs all shutdown steps for observability

Test script validates:
- Server startup and API functionality
- Graceful shutdown sequence
- JSON log format validation
- Complete log sequence verification
- Proper signal handling and context propagation

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
Gabriel Radureau
2026-04-03 19:23:23 +02:00
parent 736ec9c996
commit 7c5e61c386
9 changed files with 317 additions and 60 deletions

View File

@@ -2,14 +2,12 @@ package server
import (
"net/http"
"os"
"time"
"DanceLessonsCoach/pkg/config"
"DanceLessonsCoach/pkg/greet"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
@@ -17,18 +15,7 @@ type Server struct {
router *chi.Mux
}
func NewServer() *Server {
// Initialize Zerolog with Trace level
zerolog.SetGlobalLevel(zerolog.TraceLevel)
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
// Configure logging with optional color support
consoleWriter := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
if os.Getenv("DLC_NO_COLOR") == "1" {
consoleWriter.NoColor = true // Disable colors when DLC_NO_COLOR=1
}
log.Logger = log.Output(consoleWriter)
func NewServer(cfg *config.Config) *Server {
s := &Server{
router: chi.NewRouter(),
}