feat(otel): don't log requests if otel enabled
All checks were successful
Build and Push Docker Image / Build-And-Push-Docker-Image (push) Successful in 1m20s

This commit is contained in:
2026-01-02 18:25:34 +01:00
parent ada411e1eb
commit b5ab697cca
2 changed files with 27 additions and 20 deletions

View File

@@ -30,8 +30,8 @@ func Run(ctx context.Context, database *sqlx.DB, migrationsPrefix string, env fu
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer cancel()
otelEnabled := core.IsOtelEnabled(env)
if otelEnabled {
isOtelEnabled := core.IsOtelEnabled(env)
if isOtelEnabled {
// use context.Background(), otherwise the shutdown can't be called, as the context is already cancelled
otelShutdown, err := setupOTelSDK(context.Background())
if err != nil {
@@ -67,7 +67,7 @@ func Run(ctx context.Context, database *sqlx.DB, migrationsPrefix string, env fu
// init server
httpServer := &http.Server{
Addr: ":" + serverSettings.Port,
Handler: createHandlerWithServices(ctx, database, serverSettings),
Handler: createHandlerWithServices(ctx, database, serverSettings, isOtelEnabled),
ReadHeaderTimeout: 2 * time.Second,
}
go startServer(ctx, httpServer)
@@ -106,7 +106,7 @@ func shutdownServer(ctx context.Context, s *http.Server, wg *sync.WaitGroup) {
}
}
func createHandlerWithServices(ctx context.Context, d *sqlx.DB, serverSettings *core.Settings) http.Handler {
func createHandlerWithServices(ctx context.Context, d *sqlx.DB, serverSettings *core.Settings, isOtelEnabled bool) http.Handler {
var router = http.NewServeMux()
authDb := authentication.NewDbSqlite(d)
@@ -155,7 +155,7 @@ func createHandlerWithServices(ctx context.Context, d *sqlx.DB, serverSettings *
middleware.CrossSiteRequestForgery(authService),
middleware.Authenticate(authService),
middleware.Gzip,
middleware.Log,
middleware.Log(isOtelEnabled),
)
wrapper = otelhttp.NewHandler(wrapper, "http.request")

View File

@@ -17,8 +17,14 @@ func (w *WrappedWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
}
func Log(next http.Handler) http.Handler {
func Log(enabled bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !enabled {
next.ServeHTTP(w, r)
return
}
start := time.Now()
wrapped := &WrappedWriter{
@@ -35,3 +41,4 @@ func Log(next http.Handler) http.Handler {
"duration", time.Since(start).String())
})
}
}