From 547ab64c20717026b67b0cb1762671ee85ffd07a Mon Sep 17 00:00:00 2001 From: Andre Medeiros Date: Fri, 15 Jul 2022 12:19:27 -0400 Subject: [PATCH] add request ids to logs --- Makefile | 2 +- internal/api/api.go | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4014d3d..90780ea 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ BREW_PREFIX ?= $(shell brew --prefix) DATABASE_URL ?= "postgres://$(USER)@localhost/apollo_test?sslmode=disable" test: - @DATABASE_URL=$(DATABASE_URL) go test -race -v -timeout 1s ./... + @DATABASE_URL=$(DATABASE_URL) go test -race -timeout 1s ./... test-setup: $(BREW_PREFIX)/bin/migrate migrate -path migrations/ -database $(DATABASE_URL) up diff --git a/internal/api/api.go b/internal/api/api.go index cc52b70..0465365 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -11,6 +11,7 @@ import ( "github.com/DataDog/datadog-go/statsd" "github.com/bugsnag/bugsnag-go/v2" "github.com/go-redis/redis/v8" + "github.com/gofrs/uuid" "github.com/gorilla/mux" "github.com/jackc/pgx/v4/pgxpool" "github.com/sideshow/apns2/token" @@ -122,6 +123,7 @@ func (a *api) Routes() *mux.Router { r.HandleFunc("/v1/test/bugsnag", a.testBugsnagHandler).Methods("POST") r.Use(a.loggingMiddleware) + r.Use(a.requestIdMiddleware) return r } @@ -155,6 +157,14 @@ func (lrw *LoggingResponseWriter) WriteHeader(statusCode int) { lrw.statusCode = statusCode } +func (a *api) requestIdMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := uuid.Must(uuid.NewV4()).String() + w.Header().Set("X-Apollo-Request-Id", id) + next.ServeHTTP(w, r) + }) +} + func (a *api) loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Skip logging health checks @@ -187,6 +197,7 @@ func (a *api) loggingMiddleware(next http.Handler) http.Handler { zap.Int("response#bytes", lrw.bytes), zap.Int("status", lrw.statusCode), zap.String("uri", r.RequestURI), + zap.String("request#id", lrw.Header().Get("X-Apollo-Request-Id")), } if lrw.statusCode == 200 {