add request ids to logs

This commit is contained in:
Andre Medeiros 2022-07-15 12:19:27 -04:00
parent f4fea41435
commit 547ab64c20
2 changed files with 12 additions and 1 deletions

View file

@ -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

View file

@ -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 {