Skip to content

Commit

Permalink
add logs callback for debugging
Browse files Browse the repository at this point in the history
  • Loading branch information
Sagleft committed Oct 24, 2022
1 parent abb43d1 commit eff0808
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 10 deletions.
4 changes: 4 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ func (c *UtopiaClient) SetWsPort(wsPort int) *UtopiaClient {
return c
}

func (c *UtopiaClient) SetLogsCallback(cb LogCallback) {
c.logCallback = cb
}

// GetProfileStatus gets data about the status of the current account
func (c *UtopiaClient) GetProfileStatus() (map[string]interface{}, error) {
return c.apiQuery("getProfileStatus", nil)
Expand Down
20 changes: 20 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package utopiago

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestCallbackCheck(t *testing.T) {
c := UtopiaClient{}
assert.Nil(t, c.logCallback)
}

func TestLogGetMessage(t *testing.T) {
l := logData{}
require.NotPanics(t, func() {
l.getMessage()
})
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ go 1.16

require (
github.com/ctengiz/evtwebsocket v0.0.0-20180717104640-fc3583982591
github.com/sagleft/simple-cron v1.5.0
github.com/go-playground/assert v1.2.1
github.com/stretchr/testify v1.8.1
golang.org/x/net v0.0.0-20220526153639-5463443f8c37 // indirect
gopkg.in/grignaak/tribool.v1 v1.0.0-20150312065122-d6bb19d816df
)
21 changes: 19 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
github.com/ctengiz/evtwebsocket v0.0.0-20180717104640-fc3583982591 h1:I+6x3CO8LDrWNe6r6L9y3n3dYXGcKO9BKhJ/dVUYcwc=
github.com/ctengiz/evtwebsocket v0.0.0-20180717104640-fc3583982591/go.mod h1:lpk0rZYe7Oil/0fxAXpasQr7TGtHLSoFIYvk7QnpNEM=
github.com/sagleft/simple-cron v1.5.0 h1:ecLM1ScefaNN9MPz//CQnW0569zQGQSusFV6EyTqgAk=
github.com/sagleft/simple-cron v1.5.0/go.mod h1:a++6/wI1ZzgYe+lCAKlWBwR8xBYpPl1oXJpa5rUHlJI=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-playground/assert v1.2.1 h1:ad06XqC+TOv0nJWnbULSlh3ehp5uLuQEojZY5Tq8RgI=
github.com/go-playground/assert v1.2.1/go.mod h1:Lgy+k19nOB/wQG/fVSQ7rra5qYugmytMQqvQ2dgjWn8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/net v0.0.0-20220526153639-5463443f8c37 h1:lUkvobShwKsOesNfWWlCS5q7fnbG1MEliIzwu886fn8=
golang.org/x/net v0.0.0-20220526153639-5463443f8c37/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/grignaak/tribool.v1 v1.0.0-20150312065122-d6bb19d816df h1:SCh+kVSG+MN/pU/l0/3ehkc3i9T+G6AQS6jEoxM4ddY=
gopkg.in/grignaak/tribool.v1 v1.0.0-20150312065122-d6bb19d816df/go.mod h1:ikoZVciJt+u3It4kEk89OVqIKHPU9BjrgkHSr++TA2w=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
64 changes: 64 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package utopiago

import (
"fmt"
"time"
)

type LogCallback func(logMessage string)

type logData struct {
TimeCreated time.Time
Timestamp int64 // unix milli
APIURL string
APIMethod string
RequestType string
RequestData map[string]interface{}
Filters map[string]interface{}
Response []byte
Error error
Elapsed string
}

func (l *logData) setElapsedTime() {
l.Elapsed = time.Since(l.TimeCreated).String()
}

func (l *logData) useError(err error) error {
l.Error = err
l.setElapsedTime()
return err
}

func (l *logData) useResponse(response []byte) {
l.Response = response
l.setElapsedTime()
}

func (l *logData) getMessage() string {
status := "success"
if l.Error != nil {
status = "error: " + l.Error.Error()
}

return fmt.Sprintf(
"%v: %s %s -> %s. elapsed %s: %s\nrequest: %q\nfilters: %q\nresponse: %q",
l.Timestamp,
l.RequestType,
l.APIURL,
l.APIMethod,
l.Elapsed,
status,
l.RequestData,
l.Filters,
string(l.Response),
)
}

func (l *logData) handle(cb LogCallback) {
if cb == nil {
return
}

cb(l.getMessage())
}
24 changes: 18 additions & 6 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ func (c *UtopiaClient) apiQuery2JSON(
filters map[string]interface{},
timeout time.Duration,
) ([]byte, error) {

l := logData{
TimeCreated: time.Now(),
Timestamp: time.Now().UnixMilli(),
APIURL: c.getBaseURL(),
APIMethod: methodName,
RequestType: "POST",
RequestData: params,
Filters: filters,
}
defer l.handle(c.logCallback)

var query = Query{
Method: methodName,
Token: c.Token,
Expand All @@ -45,12 +57,12 @@ func (c *UtopiaClient) apiQuery2JSON(

var jsonStr, err = json.Marshal(query)
if err != nil {
return nil, errors.New("failed to decode response json: " + err.Error())
return nil, l.useError(fmt.Errorf("failed to decode response json: %w", err))
}

req, err := http.NewRequest("POST", c.getBaseURL(), bytes.NewBuffer(jsonStr))
req, err := http.NewRequest(l.RequestType, l.APIURL, bytes.NewBuffer(jsonStr))
if err != nil {
return nil, err
return nil, l.useError(fmt.Errorf("failed to create request: %w", err))
}
req.Header.Set("Content-Type", "application/json")

Expand All @@ -62,14 +74,15 @@ func (c *UtopiaClient) apiQuery2JSON(
resp, err := client.Do(req)
defer closeRequest(resp)
if err != nil {
return nil, err
return nil, l.useError(fmt.Errorf("failed to send request: %w", err))
}

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.New("failed to read response body: " + err.Error())
return nil, l.useError(fmt.Errorf("failed to read response body: %w", err))
}

l.useResponse(body)
return body, nil
}

Expand All @@ -82,7 +95,6 @@ func (c *UtopiaClient) apiQueryWithFilters(
params,
filters map[string]interface{},
) (map[string]interface{}, error) {

var r map[string]interface{}
var timeoutDuration time.Duration
if c.RequestTimeoutSeconds > 0 {
Expand Down
7 changes: 6 additions & 1 deletion structs.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package utopiago

import "github.com/ctengiz/evtwebsocket"
import (
"github.com/ctengiz/evtwebsocket"
)

// Query is a filter for API requests
type Query struct {
Expand All @@ -11,6 +13,9 @@ type Query struct {

// UtopiaClient lets you connect to Utopia Client
type UtopiaClient struct {
// protected
logCallback LogCallback

// required
Protocol string `json:"protocol"`
Host string `json:"host"`
Expand Down

0 comments on commit eff0808

Please sign in to comment.