Skip to content

Commit

Permalink
feat: move to log/slog for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesse0Michael committed Sep 15, 2023
1 parent 7adaa3f commit ac6be67
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 65 deletions.
21 changes: 10 additions & 11 deletions cmd/go-assured/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import (
"encoding/json"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"

kitlog "github.com/go-kit/kit/log"
"github.com/jesse0michael/go-rest-assured/v4/pkg/assured"
)

Expand All @@ -19,8 +19,6 @@ type Preload struct {
}

func main() {
logger := kitlog.NewLogfmtLogger(os.Stdout)

ctx, cancel := context.WithCancelCause(context.Background())
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
Expand All @@ -40,35 +38,36 @@ func main() {
client := assured.NewClient(
assured.WithPort(*port),
assured.WithCallTracking(*trackMade),
assured.WithLogger(logger),
assured.WithHost(*host),
assured.WithTLS(*tlsCert, *tlsKey))

go func() {
slog.With("port", client.Port).Info("starting go rest assured client")
if err := client.Serve(); err != nil {
_ = logger.Log("error", err.Error())
slog.With("error", err).Info("rest assured server stopped serving")
}
}()

// If preload file specified, parse the file and load all calls into the assured client
if *preload != "" {
b, err := os.ReadFile(*preload)
if err != nil {
_ = logger.Log("fatal", err.Error())
os.Exit(1)
slog.With("error", err).Info("failed to read preload file")
cancel(err)
}
var preload Preload
// TODO response won't unmarshal string to []byte
if err := json.Unmarshal(b, &preload); err != nil {
_ = logger.Log("fatal", err.Error())
os.Exit(1)
slog.With("error", err).Info("failed to unmarshal preload file")
cancel(err)
}
if err = client.Given(preload.Calls...); err != nil {
_ = logger.Log("fatal", err.Error())
os.Exit(1)
slog.With("error", err).Info("failed to set given preload file calls")
cancel(err)
}
}

<-ctx.Done()
client.Close()
slog.Info("exiting go rest assured")
}
7 changes: 0 additions & 7 deletions pkg/assured/bindings.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ const (

// Serve starts the Rest Assured client to begin listening on the application endpoints
func (c *Client) Serve() error {
_ = c.logger.Log("message", "starting go rest assured", "port", c.Port)
if c.tlsCertFile != "" && c.tlsKeyFile != "" {
return http.ServeTLS(c.listener, handlers.RecoveryHandler()(c.router), c.tlsCertFile, c.tlsKeyFile)
} else {
Expand Down Expand Up @@ -54,7 +53,6 @@ func (c *Client) createApplicationRouter() *mux.Router {
e.WrappedEndpoint(e.GivenEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(c.logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -64,7 +62,6 @@ func (c *Client) createApplicationRouter() *mux.Router {
e.WrappedEndpoint(e.GivenCallbackEndpoint),
decodeAssuredCallback,
encodeAssuredCall,
kithttp.ServerErrorLogger(c.logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -74,7 +71,6 @@ func (c *Client) createApplicationRouter() *mux.Router {
e.WrappedEndpoint(e.WhenEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(c.logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -84,7 +80,6 @@ func (c *Client) createApplicationRouter() *mux.Router {
e.WrappedEndpoint(e.VerifyEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(c.logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -94,7 +89,6 @@ func (c *Client) createApplicationRouter() *mux.Router {
e.WrappedEndpoint(e.ClearEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(c.logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -104,7 +98,6 @@ func (c *Client) createApplicationRouter() *mux.Router {
e.ClearAllEndpoint,
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(c.logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(http.MethodDelete)

Expand Down
3 changes: 2 additions & 1 deletion pkg/assured/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"log/slog"
"net"
"net/http"
"strconv"
Expand All @@ -30,7 +31,7 @@ func NewClient(opts ...Option) *Client {
var err error
c.listener, err = net.Listen("tcp", fmt.Sprintf(":%d", c.Options.Port))
if err != nil {
_ = c.logger.Log("error", err.Error())
slog.With("error", err, "port", c.Options.Port).Error("unable to create http listener")
}

c.Options.Port = c.listener.Addr().(*net.TCPAddr).Port
Expand Down
24 changes: 11 additions & 13 deletions pkg/assured/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,16 @@ import (
"bytes"
"context"
"errors"
"log/slog"
"net/http"
"strconv"
"time"

"github.com/go-kit/kit/endpoint"
kitlog "github.com/go-kit/kit/log"
)

// AssuredEndpoints
type AssuredEndpoints struct {
logger kitlog.Logger
httpClient *http.Client
assuredCalls *CallStore
madeCalls *CallStore
Expand All @@ -28,7 +27,6 @@ func NewAssuredEndpoints(options Options) *AssuredEndpoints {
assuredCalls: NewCallStore(),
madeCalls: NewCallStore(),
callbackCalls: NewCallStore(),
logger: options.logger,
httpClient: options.httpClient,
trackMadeCalls: options.trackMadeCalls,
}
Expand All @@ -49,15 +47,15 @@ func (a *AssuredEndpoints) WrappedEndpoint(handler func(context.Context, *Call)
// GivenEndpoint is used to stub out a call for a given path
func (a *AssuredEndpoints) GivenEndpoint(ctx context.Context, call *Call) (interface{}, error) {
a.assuredCalls.Add(call)
_ = a.logger.Log("message", "assured call set", "path", call.ID())
slog.With("path", call.ID()).Info("assured call set")

return call, nil
}

// GivenCallbackEndpoint is used to stub out callbacks for a callback key
func (a *AssuredEndpoints) GivenCallbackEndpoint(ctx context.Context, call *Call) (interface{}, error) {
a.callbackCalls.AddAt(call.Headers[AssuredCallbackKey], call)
_ = a.logger.Log("message", "assured callback set", "key", call.Headers[AssuredCallbackKey], "target", call.Headers[AssuredCallbackTarget])
slog.With("key", call.Headers[AssuredCallbackKey], "target", call.Headers[AssuredCallbackTarget]).Info("assured callback set")

return call, nil
}
Expand All @@ -66,7 +64,7 @@ func (a *AssuredEndpoints) GivenCallbackEndpoint(ctx context.Context, call *Call
func (a *AssuredEndpoints) WhenEndpoint(ctx context.Context, call *Call) (interface{}, error) {
calls := a.assuredCalls.Get(call.ID())
if len(calls) == 0 {
_ = a.logger.Log("message", "assured call not found", "path", call.ID())
slog.With("path", call.ID()).Info("assured call not found")
return nil, errors.New("No assured calls")
}

Expand All @@ -86,7 +84,7 @@ func (a *AssuredEndpoints) WhenEndpoint(ctx context.Context, call *Call) (interf
time.Sleep(time.Duration(delay) * time.Second)
}

_ = a.logger.Log("message", "assured call responded", "path", call.ID())
slog.With("path", call.ID()).Info("assured call responded")
return assured, nil
}

Expand All @@ -102,10 +100,10 @@ func (a *AssuredEndpoints) VerifyEndpoint(ctx context.Context, call *Call) (inte
func (a *AssuredEndpoints) ClearEndpoint(ctx context.Context, call *Call) (interface{}, error) {
a.assuredCalls.Clear(call.ID())
a.madeCalls.Clear(call.ID())
_ = a.logger.Log("message", "cleared calls for path", "path", call.ID())
slog.With("path", call.ID()).Info("cleared calls for path")
if call.Headers[AssuredCallbackKey] != "" {
a.callbackCalls.Clear(call.Headers[AssuredCallbackKey])
_ = a.logger.Log("message", "cleared callbacks for key", "key", call.Headers[AssuredCallbackKey])
slog.With("key", call.Headers[AssuredCallbackKey]).Info("cleared calls for key")
}

return nil, nil
Expand All @@ -116,7 +114,7 @@ func (a *AssuredEndpoints) ClearAllEndpoint(ctx context.Context, i interface{})
a.assuredCalls.ClearAll()
a.madeCalls.ClearAll()
a.callbackCalls.ClearAll()
_ = a.logger.Log("message", "cleared all calls")
slog.Info("cleared all calls")

return nil, nil
}
Expand All @@ -129,7 +127,7 @@ func (a *AssuredEndpoints) sendCallback(target string, call *Call) {
}
req, err := http.NewRequest(call.Method, target, bytes.NewBuffer(call.Response))
if err != nil {
_ = a.logger.Log("message", "failed to build callback request", "target", target, "error", err.Error())
slog.With("target", target, "error", err).Info("failed to build callback request")
return
}
for key, value := range call.Headers {
Expand All @@ -139,8 +137,8 @@ func (a *AssuredEndpoints) sendCallback(target string, call *Call) {
time.Sleep(time.Duration(delay) * time.Second)
resp, err := a.httpClient.Do(req)
if err != nil {
_ = a.logger.Log("message", "failed to reach callback target", "target", target, "error", err.Error())
slog.With("target", target, "error", err).Info("failed to reach callback target")
return
}
_ = a.logger.Log("message", "sent callback to target", "target", target, "status_code", resp.StatusCode)
slog.With("target", target, "status_code", resp.StatusCode).Info("sent callback to target")
}
10 changes: 0 additions & 10 deletions pkg/assured/endpoints_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@ package assured

import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

kitlog "github.com/go-kit/kit/log"
"github.com/stretchr/testify/require"
)

func TestNewAssuredEndpoints(t *testing.T) {
expected := &AssuredEndpoints{
logger: kitlog.NewNopLogger(),
httpClient: http.DefaultClient,
assuredCalls: NewCallStore(),
madeCalls: NewCallStore(),
Expand Down Expand Up @@ -120,7 +117,6 @@ func TestGivenCallbackEndpointSuccess(t *testing.T) {

func TestWhenEndpointSuccess(t *testing.T) {
endpoints := &AssuredEndpoints{
logger: DefaultOptions.logger,
assuredCalls: fullAssuredCalls,
madeCalls: NewCallStore(),
callbackCalls: NewCallStore(),
Expand Down Expand Up @@ -153,7 +149,6 @@ func TestWhenEndpointSuccess(t *testing.T) {

func TestWhenEndpointSuccessTrackingDisabled(t *testing.T) {
endpoints := &AssuredEndpoints{
logger: DefaultOptions.logger,
assuredCalls: fullAssuredCalls,
madeCalls: NewCallStore(),
callbackCalls: NewCallStore(),
Expand Down Expand Up @@ -194,7 +189,6 @@ func TestWhenEndpointSuccessCallbacks(t *testing.T) {
call := testCallback()
call.Headers[AssuredCallbackTarget] = testServer.URL
endpoints := &AssuredEndpoints{
logger: DefaultOptions.logger,
httpClient: http.DefaultClient,
assuredCalls: &CallStore{
data: map[string][]*Call{"GET:test/assured": {assured}},
Expand Down Expand Up @@ -227,7 +221,6 @@ func TestWhenEndpointSuccessDelayed(t *testing.T) {
call.Headers[AssuredCallbackTarget] = testServer.URL
call.Headers[AssuredCallbackDelay] = "4"
endpoints := &AssuredEndpoints{
logger: DefaultOptions.logger,
httpClient: http.DefaultClient,
assuredCalls: &CallStore{
data: map[string][]*Call{"GET:test/assured": {assured}},
Expand Down Expand Up @@ -313,7 +306,6 @@ func TestVerifyEndpointTrackingDisabled(t *testing.T) {

func TestClearEndpointSuccess(t *testing.T) {
endpoints := &AssuredEndpoints{
logger: kitlog.NewLogfmtLogger(io.Discard),
assuredCalls: fullAssuredCalls,
madeCalls: fullAssuredCalls,
callbackCalls: NewCallStore(),
Expand Down Expand Up @@ -347,7 +339,6 @@ func TestClearEndpointSuccess(t *testing.T) {

func TestClearEndpointSuccessCallback(t *testing.T) {
endpoints := &AssuredEndpoints{
logger: kitlog.NewLogfmtLogger(io.Discard),
assuredCalls: fullAssuredCalls,
madeCalls: NewCallStore(),
callbackCalls: &CallStore{
Expand All @@ -370,7 +361,6 @@ func TestClearEndpointSuccessCallback(t *testing.T) {

func TestClearAllEndpointSuccess(t *testing.T) {
endpoints := &AssuredEndpoints{
logger: kitlog.NewLogfmtLogger(io.Discard),
assuredCalls: fullAssuredCalls,
madeCalls: fullAssuredCalls,
callbackCalls: fullAssuredCalls,
Expand Down
13 changes: 0 additions & 13 deletions pkg/assured/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ package assured

import (
"net/http"

kitlog "github.com/go-kit/kit/log"
)

var DefaultOptions = Options{
logger: kitlog.NewNopLogger(),
httpClient: http.DefaultClient,
host: "localhost",
trackMadeCalls: true,
Expand All @@ -18,9 +15,6 @@ type Option func(*Options)

// Options can be used to configure the rest assured client.
type Options struct {
// logger used by the rest assured client
logger kitlog.Logger

// httpClient used to interact with the rest assured server
httpClient *http.Client

Expand All @@ -40,13 +34,6 @@ type Options struct {
trackMadeCalls bool
}

// WithLogger sets the logger to be used.
func WithLogger(l kitlog.Logger) Option {
return func(o *Options) {
o.logger = l
}
}

// WithHTTPClient sets the http client option.
func WithHTTPClient(c http.Client) Option {
return func(o *Options) {
Expand Down
10 changes: 0 additions & 10 deletions pkg/assured/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,14 @@ import (
"net/http"
"reflect"
"testing"

kitlog "github.com/go-kit/kit/log"
)

func Test_applyOptions(t *testing.T) {
log := kitlog.NewNopLogger()
tests := []struct {
name string
option Option
want Options
}{
{
name: "with logger",
option: WithLogger(log),
want: Options{
logger: log,
},
},
{
name: "with http client",
option: WithHTTPClient(*http.DefaultClient),
Expand Down

0 comments on commit ac6be67

Please sign in to comment.