Пример #1
1
// LogRequests logs the requests to the embedded logger.
func LogRequests(h httpx.Handler) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		logger.Info(ctx, "request.start",
			"method", r.Method,
			"path", r.URL.Path,
		)

		err := h.ServeHTTPContext(ctx, w, r)

		logger.Info(ctx, "request.complete")

		return err
	})
}
Пример #2
0
// InsertLogger returns an httpx.Handler middleware that will call f to generate
// a logger, then insert it into the context.
func InsertLogger(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		l := f(ctx, r)
		ctx = logger.WithLogger(ctx, l)
		return h.ServeHTTPContext(ctx, w, r)
	})
}
Пример #3
0
// PrefixRequestID adds the request as a prefix to the log15.Logger.
func PrefixRequestID(h httpx.Handler) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		if l, ok := logger.FromContext(ctx); ok {
			if l, ok := l.(log15.Logger); ok {
				ctx = logger.WithLogger(ctx, l.New("request_id", httpx.RequestID(ctx)))
			}
		}

		return h.ServeHTTPContext(ctx, w, r)
	})
}
Пример #4
0
// WithRequest adds information about the http.Request to reported errors.
func WithRequest(h httpx.Handler) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		ctx = httpx.WithRequest(ctx, r)

		// Add the request to the context.
		reporter.AddRequest(ctx, r)

		// Add the request id
		reporter.AddContext(ctx, "request_id", httpx.RequestID(ctx))

		return h.ServeHTTPContext(ctx, w, r)
	})
}
Пример #5
0
func traceTest(t *testing.T, tt *tracerTest) {
	var m httpx.Handler
	r := httpx.NewRouter()

	if tt.routes != nil {
		tt.routes(r)
	}

	tx := new(mockTx)
	m = &NewRelicTracer{
		handler: r,
		router:  r,
		tracer:  nil,
		createTx: func(transactionName, url string, tracer newrelic.TxTracer) newrelic.Tx {
			if tt.expectedTransactionName != transactionName {
				t.Fatalf("Transaction mismatch expected: %v got: %v", tt.expectedTransactionName, transactionName)
			}
			if tt.expectedUrl != url {
				t.Fatalf("Url mismatch expected: %v got: %v", tt.expectedUrl, url)
			}
			return tx
		},
	}

	ctx := context.Background()
	resp := httptest.NewRecorder()

	tx.On("Start").Return(nil)
	tx.On("End").Return(nil)

	if err := m.ServeHTTPContext(ctx, resp, tt.req); err != nil {
		t.Fatal(err)
	}

	tx.AssertExpectations(t)
}
Пример #6
0
// Handler adapts an httpx.Handler to an http.Handler using the provided root
// context.
func Handler(root context.Context, h httpx.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h.ServeHTTPContext(root, w, r)
	})
}