Skip to content

Commit

Permalink
feat: add debug http logging (#346)
Browse files Browse the repository at this point in the history
Add optional debug logging for dumping http requests and responses.

Signed-off-by: Blake Pettersson <[email protected]>
  • Loading branch information
blakepettersson committed Sep 22, 2023
1 parent fbfb7b1 commit 5e8275d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
37 changes: 37 additions & 0 deletions pkg/target/http/logroundtripper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package http

import (
"fmt"
"go.uber.org/zap"
"net/http"
"net/http/httputil"
)

func NewLoggingRoundTripper(roundTripper http.RoundTripper) http.RoundTripper {
return &logRoundTripper{roundTripper: roundTripper}
}

type logRoundTripper struct {
roundTripper http.RoundTripper
}

func (rt *logRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
logger := zap.L()
if logger.Core().Enabled(zap.DebugLevel) {
if info, err := httputil.DumpRequest(req, true); err == nil {
logger.Debug(fmt.Sprintf("Sending request: %s", string(info)))
if err != nil {
return nil, err
}
}
}
resp, err := rt.roundTripper.RoundTrip(req)
if resp != nil {
if logger.Core().Enabled(zap.DebugLevel) {
if info, err := httputil.DumpResponse(resp, true); err == nil {
logger.Debug(fmt.Sprintf("Received response: %s", string(info)))
}
}
}
return resp, err
}
6 changes: 3 additions & 3 deletions pkg/target/http/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"io/ioutil"
"net/http"
"os"
"time"

"go.uber.org/zap"
Expand Down Expand Up @@ -86,11 +86,11 @@ func NewClient(certificatePath string, skipTLS bool) *http.Client {
}

client := &http.Client{
Transport: transport,
Transport: NewLoggingRoundTripper(transport),
}

if certificatePath != "" {
caCert, err := ioutil.ReadFile(certificatePath)
caCert, err := os.ReadFile(certificatePath)
if err != nil {
zap.L().Error("failed to read certificate", zap.String("path", certificatePath))
return client
Expand Down

0 comments on commit 5e8275d

Please sign in to comment.