Skip to content

Commit

Permalink
add request ids to logs
Browse files Browse the repository at this point in the history
  • Loading branch information
andremedeiros committed Jul 15, 2022
1 parent f4fea41 commit 547ab64
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 547ab64

Please sign in to comment.