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

Added optional request and response logging #6

Closed
wants to merge 9 commits into from
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.DS_Store
debug.test
.idea
33 changes: 33 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,36 @@ client.SetUserAgent("your-user-agent-value")

// send API request...
```

# Logging

## Adding a custom logger

You can add a custom logger to the client that will be used to print outgoing requests and incoming responses. Debug
mode must be set to `true` to enable logging.

This is an example of how to enable logging and log to a file:

```go
// Create a logger, which outputs to file.
f, err := os.OpenFile("log.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be // handle error

}
defer f.Close()

fileLogger := &log.Logger{}
fileLogger.SetOutput(f)

client, err := helix.NewClient(&helix.Options{
logger: fileLogger,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logger needs to be capitalised (ie. Logger).

debug: true,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

debug needs to be capitalised (ie. Debug).

})
if err != nil {
log.Fatalf("error opening file: %v", err)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be // handle error


}
```

Should you want to enable debug mode but not want to use a custom logger, stdout will be used as the default log output.

42 changes: 42 additions & 0 deletions helix.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -39,6 +41,10 @@ type Client struct {

baseURL string
lastResponse *Response

// Logging
debug bool
logger *log.Logger
}

// Options ...
Expand All @@ -52,6 +58,8 @@ type Options struct {
Scopes []string
HTTPClient HTTPClient
RateLimitFunc RateLimitFunc
Debug bool
Logger *log.Logger
}

// RateLimitFunc ...
Expand Down Expand Up @@ -108,9 +116,17 @@ func NewClient(options *Options) (*Client, error) {
c := &Client{
clientID: options.ClientID,
httpClient: http.DefaultClient,
logger: options.Logger,
debug: options.Debug,
}

// Set options

// Use the default logger, if none was set by the user.
if options.Logger == nil {
c.logger = log.New(os.Stdout, "Helix: ", log.LstdFlags)
}

if options.HTTPClient != nil {
c.httpClient = options.HTTPClient
}
Expand Down Expand Up @@ -151,11 +167,19 @@ func (c *Client) sendRequest(method, path string, respData, reqData interface{})
return nil, err
}

if c.debug {
c.logger.Printf("%+v\n", req)
}

err = c.doRequest(req, resp)
if err != nil {
return nil, err
}

if c.debug {
c.logger.Printf("%+v\n", resp)
}

return resp, nil
}

Expand Down Expand Up @@ -279,12 +303,30 @@ func (c *Client) doRequest(req *http.Request, resp *Response) error {
}
}

// Dump request on debug.
if c.debug {
bodyBytes, err := httputil.DumpRequest(req, true)
if err != nil {
return fmt.Errorf("Failed to dump API request: %s", err.Error())
}
c.logger.Println(string(bodyBytes))
}

response, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("Failed to execute API request: %s", err.Error())
}
defer response.Body.Close()

// Dump response on debug.
if c.debug {
bodyBytes, err := httputil.DumpResponse(response, true)
if err != nil {
return fmt.Errorf("Failed to dump API response: %s", err.Error())
}
c.logger.Println(string(bodyBytes))
}

resp.Header = response.Header

setResponseStatusCode(resp, "StatusCode", response.StatusCode)
Expand Down