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

enable passing custom logger #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 57 additions & 16 deletions logRequests.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,71 @@
package transport

import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"

"moul.io/http2curl/v2"
)

func LogRequests(next http.RoundTripper) http.RoundTripper {
return RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) {
r := CloneRequest(req)
type RequestLogger interface {
LogRequest(req *http.Request, curl *http2curl.CurlCommand)
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not a fan of http2curl being part of any public interface

Copy link
Author

Choose a reason for hiding this comment

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

Makes sense. Should I pass string directly ?

LogResponse(r *http.Request, resp *http.Response, startTime time.Time)
}

curlCommand, _ := http2curl.GetCurlCommand(r)
log.Printf("%v", curlCommand)
log.Printf("request: %s %s", r.Method, r.URL)
func LogRequests(logger RequestLogger) func(next http.RoundTripper) http.RoundTripper {
return func(next http.RoundTripper) http.RoundTripper {
return RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) {
r := CloneRequest(req)

startTime := time.Now()
defer func() {
if resp != nil {
log.Printf("response (HTTP %v): %v %s", time.Since(startTime), resp.Status, r.URL)
} else {
log.Printf("response (<nil>): %v %s", time.Since(startTime), r.URL)
}
}()
curlCommand, _ := http2curl.GetCurlCommand(r)

logger.LogRequest(req, curlCommand)

startTime := time.Now()
defer func() {
logger.LogResponse(r, resp, startTime)
}()

return next.RoundTrip(r)
})
}
}

type DefaultLogger struct {
PrintResponsePayload bool
}

return next.RoundTrip(r)
})
func (d *DefaultLogger) LogRequest(r *http.Request, curl *http2curl.CurlCommand) {
log.Printf(curl.String())
log.Printf("request: %s %s", r.Method, r.URL)
}

func (d *DefaultLogger) LogResponse(r *http.Request, resp *http.Response, startTime time.Time) {
if resp == nil {
log.Printf(fmt.Sprintf("response (<nil>): %v %s", time.Since(startTime), r.URL))
return
}

log.Printf("response: %s %s", resp.Status, resp.Request.URL)

if d.PrintResponsePayload && resp.Header.Get("Content-Type") == "application/json" {
var b bytes.Buffer

tee := io.TeeReader(resp.Body, &b)
resp.Body = io.NopCloser(&b)

payload, err := io.ReadAll(tee)
if err == nil {
// Pretty print the JSON payload
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, payload, "", " "); err == nil {
log.Printf("%s", prettyJSON.String())
}
}
}
}
2 changes: 1 addition & 1 deletion setHeaderFunc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestSetHeaderFunc(t *testing.T) {
Transport: transport.Chain(
http.DefaultTransport,
transport.SetHeaderFunc("Authorization", issueRandomAuthToken),
transport.LogRequests,
transport.LogRequests(&transport.DefaultLogger{PrintResponsePayload: true}),
),
Timeout: 15 * time.Second,
}
Expand Down
2 changes: 1 addition & 1 deletion setHeader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestSetHeader(t *testing.T) {
transport.SetHeader("User-Agent", userAgent),
transport.SetHeader("Authorization", authHeader),
transport.SetHeader("x-extra", "value"),
transport.LogRequests,
transport.LogRequests(&transport.DefaultLogger{PrintResponsePayload: true}),
),
Timeout: 15 * time.Second,
}
Expand Down
6 changes: 3 additions & 3 deletions transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestChain(t *testing.T) {
Transport: Chain(
nil,
SetHeader("User-Agent", "transport-chain/v1.0.0"),
LogRequests,
LogRequests(&DefaultLogger{PrintResponsePayload: true}),
),
}

Expand Down Expand Up @@ -63,7 +63,7 @@ func TestChainWithRetries(t *testing.T) {
Transport: Chain(
http.DefaultTransport,
Retry(http.DefaultTransport, 5),
LogRequests,
LogRequests(&DefaultLogger{PrintResponsePayload: true}),
),
}

Expand Down Expand Up @@ -103,7 +103,7 @@ func TestChainWithRetryAfter(t *testing.T) {
Transport: Chain(
http.DefaultTransport,
Retry(http.DefaultTransport, 5),
LogRequests,
LogRequests(&DefaultLogger{PrintResponsePayload: true}),
),
}

Expand Down
Loading