Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support/http: allow services to specify the logger used by the logging middleware #2314

Merged
merged 4 commits into from
Feb 24, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion exp/services/recoverysigner/internal/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ func getHandlerDeps(opts Options) (handlerDeps, error) {
}

func handler(deps handlerDeps) http.Handler {
mux := supporthttp.NewAPIMux()
mux := supporthttp.NewAPIMux(deps.Logger)

mux.NotFound(errorHandler{Error: notFound}.ServeHTTP)
mux.MethodNotAllowed(errorHandler{Error: methodNotAllowed}.ServeHTTP)
Expand Down
2 changes: 1 addition & 1 deletion exp/services/webauth/internal/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func handler(opts Options) (http.Handler, error) {
}
horizonClient.SetHorizonTimeOut(uint(horizonTimeout / time.Second))

mux := supporthttp.NewAPIMux()
mux := supporthttp.NewAPIMux(opts.Logger)

mux.NotFound(errorHandler{Error: notFound}.ServeHTTP)
mux.MethodNotAllowed(errorHandler{Error: methodNotAllowed}.ServeHTTP)
Expand Down
3 changes: 2 additions & 1 deletion services/bridge/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/stellar/go/support/db/schema"
"github.com/stellar/go/support/errors"
supportHttp "github.com/stellar/go/support/http"
supportLog "github.com/stellar/go/support/log"
)

var app *App
Expand Down Expand Up @@ -231,7 +232,7 @@ func NewApp(config config.Config, migrateFlag bool, versionFlag bool, version st

// Serve starts the server
func (a *App) Serve() {
mux := supportHttp.NewAPIMux()
mux := supportHttp.NewAPIMux(supportLog.DefaultLogger)

// Middlewares
headers := make(http.Header)
Expand Down
5 changes: 3 additions & 2 deletions services/compliance/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/stellar/go/support/db/schema"
"github.com/stellar/go/support/errors"
supportHttp "github.com/stellar/go/support/http"
supportLog "github.com/stellar/go/support/log"
)

var app *App
Expand Down Expand Up @@ -170,7 +171,7 @@ func NewApp(config config.Config, migrateFlag bool, versionFlag bool, version st
// Serve starts the server
func (a *App) Serve() {
// External endpoints
external := supportHttp.NewAPIMux()
external := supportHttp.NewAPIMux(supportLog.DefaultLogger)

// Middlewares
headers := http.Header{}
Expand All @@ -195,7 +196,7 @@ func (a *App) Serve() {
}()

// Internal endpoints
internal := supportHttp.NewAPIMux()
internal := supportHttp.NewAPIMux(supportLog.DefaultLogger)

internal.Use(supportHttp.StripTrailingSlashMiddleware("/admin"))
internal.Use(supportHttp.HeadersMiddleware(headers, "/admin/"))
Expand Down
2 changes: 1 addition & 1 deletion services/federation/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func initDriver(cfg Config) (federation.Driver, error) {
}

func initMux(driver federation.Driver) *chi.Mux {
mux := http.NewAPIMux()
mux := http.NewAPIMux(log.DefaultLogger)

fed := &federation.Handler{
Driver: driver,
Expand Down
2 changes: 1 addition & 1 deletion services/friendbot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func run(cmd *cobra.Command, args []string) {
}

func initRouter(fb *internal.Bot) *chi.Mux {
mux := http.NewAPIMux()
mux := http.NewAPIMux(log.DefaultLogger)

handler := &internal.FriendbotHandler{Friendbot: fb}
mux.Get("/", handler.Handle)
Expand Down
12 changes: 12 additions & 0 deletions support/http/logging_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ import (
"github.com/stellar/go/support/log"
)

// SetLogger is a middleware that sets a logger on the context.
func SetLoggerMiddleware(l *log.Entry) func(stdhttp.Handler) stdhttp.Handler {
return func(next stdhttp.Handler) stdhttp.Handler {
return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
ctx := r.Context()
ctx = log.Set(ctx, l)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}

// LoggingMiddleware is a middleware that logs requests to the logger.
func LoggingMiddleware(next stdhttp.Handler) stdhttp.Handler {
return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
Expand Down
35 changes: 35 additions & 0 deletions support/http/logging_middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,38 @@ func TestHTTPMiddleware(t *testing.T) {
assert.NotEmpty(t, line.Data["path"])
}
}

func TestHTTPMiddlewareWithLoggerSet(t *testing.T) {
logger := log.New()
done := logger.StartTest(log.InfoLevel)
mux := chi.NewMux()

mux.Use(middleware.RequestID)
mux.Use(SetLoggerMiddleware(logger))
mux.Use(LoggingMiddleware)

mux.Get("/", stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
}))
mux.Handle("/not_found", stdhttp.NotFoundHandler())

src := httptest.NewServer(t, mux)
src.GET("/").Expect().Status(stdhttp.StatusOK)
src.GET("/not_found").Expect().Status(stdhttp.StatusNotFound)

// get the log buffer and ensure it has both the start and end log lines for
// each request
logged := done()
if assert.Len(t, logged, 4, "unexpected log line count") {
assert.Equal(t, "starting request", logged[0].Message)
assert.Equal(t, "starting request", logged[2].Message)
assert.Equal(t, "finished request", logged[1].Message)
assert.Equal(t, "finished request", logged[3].Message)
}

for _, line := range logged {
assert.Equal(t, "http", line.Data["subsys"])
assert.Equal(t, "GET", line.Data["method"])
assert.NotEmpty(t, line.Data["req"])
assert.NotEmpty(t, line.Data["path"])
}
}
10 changes: 7 additions & 3 deletions support/http/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,28 @@ import (
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/rs/cors"
"github.com/stellar/go/support/log"
)

// NewMux returns a new server mux configured with the common defaults used across all
// stellar services.
func NewMux() *chi.Mux {
func NewMux(l *log.Entry) *chi.Mux {
mux := chi.NewMux()

mux.Use(middleware.RequestID)
mux.Use(middleware.Recoverer)
if l != nil {
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
mux.Use(SetLoggerMiddleware(l))
}
mux.Use(LoggingMiddleware)

return mux
}

// NewAPIMux returns a new server mux configured with the common defaults used for a web API in
// stellar.
func NewAPIMux() *chi.Mux {
mux := NewMux()
func NewAPIMux(l *log.Entry) *chi.Mux {
mux := NewMux(l)

c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
Expand Down
4 changes: 2 additions & 2 deletions support/render/health/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

func ExampleResponse() {
mux := supporthttp.NewAPIMux()
mux := supporthttp.NewAPIMux(nil)

mux.Get("/health", func(w http.ResponseWriter, r *http.Request) {
healthCheckResult := false
Expand Down Expand Up @@ -44,7 +44,7 @@ func ExampleResponse() {
}

func ExampleHandler() {
mux := supporthttp.NewAPIMux()
mux := supporthttp.NewAPIMux(nil)

mux.Get("/health", health.PassHandler{}.ServeHTTP)

Expand Down