feat(http): lab6 add OTel spans, metrics, JSON logs and tracing readiness

This commit is contained in:
Голиков Maximillian Антон
2026-11-16 09:21:23 +03:00
parent 6bc501ca3e
commit c403b23595
5 changed files with 66 additions and 6 deletions
+8 -1
View File
@@ -7,9 +7,11 @@ import (
"time"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/otel/codes"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi/dto"
"high-loud-apps-labs/internal/telemetry"
)
type HealthCheck func(ctx context.Context) error
@@ -33,12 +35,16 @@ func (h *HealthHandler) Live(c *gin.Context) {
}
func (h *HealthHandler) Ready(c *gin.Context) {
ctx, span := telemetry.Tracer("httpapi").Start(c.Request.Context(), "health.ready")
defer span.End()
if h.ready != nil && !h.ready.Load() {
span.SetStatus(codes.Error, "shutting down")
respondError(c, &domain.UnavailableError{Reason: "shutting down"})
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
for _, check := range h.checks {
@@ -46,6 +52,7 @@ func (h *HealthHandler) Ready(c *gin.Context) {
continue
}
if err := check(ctx); err != nil {
span.SetStatus(codes.Error, "зависимость недоступна")
respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"})
return
}
@@ -0,0 +1,35 @@
package middleware
import (
"log/slog"
"time"
"github.com/gin-gonic/gin"
)
// Logging записывает результат запроса с шаблоном маршрута и контекстом серверного спана.
func Logging() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
route := c.FullPath()
if route == "" {
route = "unknown"
}
status := c.Writer.Status()
level := slog.LevelInfo
if status >= 500 {
level = slog.LevelError
}
slog.LogAttrs(c.Request.Context(), level, "HTTP-запрос завершён",
slog.String("instance_id", GetInstanceID()),
slog.String("event", "http.request.completed"),
slog.String("request_id", GetRequestID(c)),
slog.String("http.request.method", c.Request.Method),
slog.String("http.route", route),
slog.Int("http.response.status_code", status),
slog.Float64("duration_seconds", time.Since(start).Seconds()),
)
}
}
+13 -3
View File
@@ -1,6 +1,9 @@
package httpapi
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/httpapi/handler"
@@ -20,12 +23,19 @@ func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
gin.EnableJsonDecoderDisallowUnknownFields()
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(middleware.RequestID())
r.Use(middleware.Instance())
r.Use(middleware.Metrics())
r.Use(middleware.OTel())
r.Use(middleware.Metrics())
r.Use(middleware.Logging())
r.Use(gin.CustomRecoveryWithWriter(nil, func(c *gin.Context, err any) {
slog.Error("Паника при обработке HTTP-запроса",
"panic", err,
"http.route", c.FullPath(),
"request_id", middleware.GetRequestID(c),
)
c.AbortWithStatus(http.StatusInternalServerError)
}))
r.GET("/health/live", h.Health.Live)
r.GET("/health/ready", h.Health.Ready)