Configure logger for connect backend

This commit is contained in:
Dan Sosedoff 2022-12-02 11:45:23 -06:00
parent f9e376a117
commit f19f165afc
No known key found for this signature in database
GPG Key ID: 26186197D282B164
6 changed files with 35 additions and 15 deletions

View File

@ -92,7 +92,7 @@ func ConnectWithBackend(c *gin.Context) {
backend := Backend{ backend := Backend{
Endpoint: command.Opts.ConnectBackend, Endpoint: command.Opts.ConnectBackend,
Token: command.Opts.ConnectToken, Token: command.Opts.ConnectToken,
PassHeaders: command.Opts.ConnectHeaders, PassHeaders: strings.Split(command.Opts.ConnectHeaders, ","),
} }
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"net/http" "net/http"
"strings" "strings"
@ -16,7 +15,7 @@ import (
type Backend struct { type Backend struct {
Endpoint string Endpoint string
Token string Token string
PassHeaders string PassHeaders []string
} }
// BackendRequest represents a payload sent to the third-party source // BackendRequest represents a payload sent to the third-party source
@ -33,6 +32,8 @@ type BackendCredential struct {
// FetchCredential sends an authentication request to a third-party service // FetchCredential sends an authentication request to a third-party service
func (be Backend) FetchCredential(ctx context.Context, resource string, c *gin.Context) (*BackendCredential, error) { func (be Backend) FetchCredential(ctx context.Context, resource string, c *gin.Context) (*BackendCredential, error) {
logger.WithField("resource", resource).Debug("fetching database credential")
request := BackendRequest{ request := BackendRequest{
Resource: resource, Resource: resource,
Token: be.Token, Token: be.Token,
@ -40,14 +41,13 @@ func (be Backend) FetchCredential(ctx context.Context, resource string, c *gin.C
} }
// Pass white-listed client headers to the backend request // Pass white-listed client headers to the backend request
for _, name := range strings.Split(be.PassHeaders, ",") { for _, name := range be.PassHeaders {
request.Headers[strings.ToLower(name)] = c.Request.Header.Get(name) request.Headers[strings.ToLower(name)] = c.Request.Header.Get(name)
} }
body, err := json.Marshal(request) body, err := json.Marshal(request)
if err != nil { if err != nil {
log.Println("[BACKEND] backend request serialization error:", err) logger.WithField("resource", resource).Error("backend request serialization error:", err)
return nil, err return nil, err
} }
@ -59,14 +59,20 @@ func (be Backend) FetchCredential(ctx context.Context, resource string, c *gin.C
resp, err := http.DefaultClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
// Any connection-related issues will show up in the server log logger.WithField("resource", resource).Error("backend credential fetch failed:", err)
log.Println("[BACKEND] unable to fetch credential:", err)
return nil, errBackendConnectError return nil, errBackendConnectError
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
return nil, fmt.Errorf("received HTTP status code %v", resp.StatusCode) err = fmt.Errorf("backend credential fetch received HTTP status code %v", resp.StatusCode)
logger.
WithField("resource", resource).
WithField("status", resp.StatusCode).
Error(err)
return nil, err
} }
cred := &BackendCredential{} cred := &BackendCredential{}

View File

@ -24,7 +24,7 @@ func TestBackendFetchCredential(t *testing.T) {
{ {
name: "Bad auth token", name: "Bad auth token",
backend: Backend{Endpoint: "http://localhost:5555/unauthorized"}, backend: Backend{Endpoint: "http://localhost:5555/unauthorized"},
err: errors.New("received HTTP status code 401"), err: errors.New("backend credential fetch received HTTP status code 401"),
}, },
{ {
name: "Backend timeout", name: "Backend timeout",
@ -42,13 +42,13 @@ func TestBackendFetchCredential(t *testing.T) {
{ {
name: "Missing header", name: "Missing header",
backend: Backend{Endpoint: "http://localhost:5555/pass-header"}, backend: Backend{Endpoint: "http://localhost:5555/pass-header"},
err: errors.New("received HTTP status code 400"), err: errors.New("backend credential fetch received HTTP status code 400"),
}, },
{ {
name: "Require header", name: "Require header",
backend: Backend{ backend: Backend{
Endpoint: "http://localhost:5555/pass-header", Endpoint: "http://localhost:5555/pass-header",
PassHeaders: "x-foo", PassHeaders: []string{"x-foo"},
}, },
reqCtx: &gin.Context{ reqCtx: &gin.Context{
Request: &http.Request{ Request: &http.Request{

View File

@ -11,6 +11,19 @@ import (
const loggerMessage = "http_request" const loggerMessage = "http_request"
var logger *logrus.Logger
func init() {
if logger == nil {
logger = logrus.New()
}
}
// TODO: Move this into server struct when it's ready
func SetLogger(l *logrus.Logger) {
logger = l
}
func RequestLogger(logger *logrus.Logger) gin.HandlerFunc { func RequestLogger(logger *logrus.Logger) gin.HandlerFunc {
debug := logger.Level > logrus.InfoLevel debug := logger.Level > logrus.InfoLevel

View File

@ -199,6 +199,7 @@ func startServer() {
router.Use(gin.BasicAuth(auth)) router.Use(gin.BasicAuth(auth))
} }
api.SetLogger(logger)
api.SetupRoutes(router) api.SetupRoutes(router)
fmt.Println("Starting server...") fmt.Println("Starting server...")

View File

@ -287,7 +287,7 @@ func testEstimatedTableRowsCount(t *testing.T) {
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
assert.Equal(t, []string{"reltuples"}, res.Columns) assert.Equal(t, []string{"reltuples"}, res.Columns)
assert.Equal(t, []Row{Row{count}}, res.Rows) assert.Equal(t, []Row{{count}}, res.Rows)
} }
func testTableRowsCount(t *testing.T) { func testTableRowsCount(t *testing.T) {
@ -296,7 +296,7 @@ func testTableRowsCount(t *testing.T) {
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
assert.Equal(t, []string{"count"}, res.Columns) assert.Equal(t, []string{"count"}, res.Columns)
assert.Equal(t, []Row{Row{count}}, res.Rows) assert.Equal(t, []Row{{count}}, res.Rows)
} }
func testTableRowsCountWithLargeTable(t *testing.T) { func testTableRowsCountWithLargeTable(t *testing.T) {
@ -307,7 +307,7 @@ func testTableRowsCountWithLargeTable(t *testing.T) {
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
assert.Equal(t, []string{"reltuples"}, res.Columns) assert.Equal(t, []string{"reltuples"}, res.Columns)
assert.Equal(t, []Row{Row{count}}, res.Rows) assert.Equal(t, []Row{{count}}, res.Rows)
} }
func testTableIndexes(t *testing.T) { func testTableIndexes(t *testing.T) {