Skip to content

Commit

Permalink
Merge pull request #89 from mackerelio/custom-logger
Browse files Browse the repository at this point in the history
add Client.Logger for custom logging
  • Loading branch information
lufia authored May 28, 2019
2 parents c64facc + 2f55415 commit 3a2ef8d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
15 changes: 12 additions & 3 deletions mackerel.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ type Client struct {
UserAgent string
AdditionalHeaders http.Header
HTTPClient *http.Client

// Logger specifies an optional logger.
// If nil, logging is done via the log package's standard logger.
Logger *log.Logger
}

// NewClient returns new mackerel.Client
Expand All @@ -40,7 +44,7 @@ func NewClientWithOptions(apikey string, rawurl string, verbose bool) (*Client,
}
client := &http.Client{}
client.Timeout = apiRequestTimeout
return &Client{u, apikey, verbose, defaultUserAgent, http.Header{}, client}, nil
return &Client{u, apikey, verbose, defaultUserAgent, http.Header{}, client, nil}, nil
}

func (c *Client) urlFor(path string) *url.URL {
Expand Down Expand Up @@ -69,10 +73,15 @@ func (c *Client) buildReq(req *http.Request) *http.Request {
func (c *Client) Request(req *http.Request) (resp *http.Response, err error) {
req = c.buildReq(req)

logPrintf := log.Printf
if c.Logger != nil {
logPrintf = c.Logger.Printf
}

if c.Verbose {
dump, err := httputil.DumpRequest(req, true)
if err == nil {
log.Printf("%s", dump)
logPrintf("%s", dump)
}
}

Expand All @@ -83,7 +92,7 @@ func (c *Client) Request(req *http.Request) (resp *http.Response, err error) {
if c.Verbose {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Printf("%s", dump)
logPrintf("%s", dump)
}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
Expand Down
20 changes: 20 additions & 0 deletions mackerel_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package mackerel

import (
"bytes"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

Expand Down Expand Up @@ -57,3 +60,20 @@ func TestBuildReq(t *testing.T) {
t.Errorf("X-Revision should be '%s' but %s", xRev, h)
}
}

func TestLogger(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("OK"))
}))
defer ts.Close()

client, _ := NewClientWithOptions("dummy-key", ts.URL, true)
var buf bytes.Buffer
client.Logger = log.New(&buf, "<api>", 0)
req, _ := http.NewRequest("GET", client.urlFor("/").String(), nil)
client.Request(req)
s := strings.TrimSpace(buf.String())
if !strings.HasPrefix(s, "<api>") || !strings.HasSuffix(s, "OK") {
t.Errorf("verbose log should match /<api>.*OK/; but %s", s)
}
}

0 comments on commit 3a2ef8d

Please sign in to comment.