Skip to content

Commit a4438a4

Browse files
authored
fix(httpclient): Fixed logger transport config (#143)
1 parent 35b3319 commit a4438a4

File tree

4 files changed

+88
-46
lines changed

4 files changed

+88
-46
lines changed

httpclient/transport/logger.go

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -65,19 +65,19 @@ func (t *LoggerTransport) Base() http.RoundTripper {
6565
func (t *LoggerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
6666
logger := log.CtxLogger(req.Context())
6767

68-
reqEvt := logger.WithLevel(t.config.LogRequestLevel)
69-
7068
if t.config.LogRequest {
69+
reqEvt := logger.WithLevel(t.config.LogRequestLevel)
70+
7171
reqDump, err := httputil.DumpRequestOut(req, t.config.LogRequestBody)
7272
if err == nil {
7373
reqEvt.Bytes("request", reqDump)
7474
}
75-
}
7675

77-
reqEvt.
78-
Str("method", req.Method).
79-
Str("url", req.URL.String()).
80-
Msg("http client request")
76+
reqEvt.
77+
Str("method", req.Method).
78+
Str("url", req.URL.String()).
79+
Msg("http client request")
80+
}
8181

8282
start := time.Now()
8383
resp, err := t.transport.RoundTrip(req)
@@ -89,34 +89,34 @@ func (t *LoggerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
8989
return resp, err
9090
}
9191

92-
var respEvt *zerolog.Event
93-
94-
if t.config.LogResponseLevelFromResponseCode {
95-
switch {
96-
case resp.StatusCode >= http.StatusBadRequest && resp.StatusCode < http.StatusInternalServerError:
97-
respEvt = logger.Warn()
98-
case resp.StatusCode >= http.StatusInternalServerError:
99-
respEvt = logger.Error()
100-
default:
92+
if t.config.LogResponse {
93+
var respEvt *zerolog.Event
94+
95+
if t.config.LogResponseLevelFromResponseCode {
96+
switch {
97+
case resp.StatusCode >= http.StatusBadRequest && resp.StatusCode < http.StatusInternalServerError:
98+
respEvt = logger.Warn()
99+
case resp.StatusCode >= http.StatusInternalServerError:
100+
respEvt = logger.Error()
101+
default:
102+
respEvt = logger.WithLevel(t.config.LogResponseLevel)
103+
}
104+
} else {
101105
respEvt = logger.WithLevel(t.config.LogResponseLevel)
102106
}
103-
} else {
104-
respEvt = logger.WithLevel(t.config.LogResponseLevel)
105-
}
106107

107-
if t.config.LogResponse {
108108
respDump, err := httputil.DumpResponse(resp, t.config.LogResponseBody)
109109
if err == nil {
110110
respEvt.Bytes("response", respDump)
111111
}
112-
}
113112

114-
respEvt.
115-
Str("method", resp.Request.Method).
116-
Str("url", resp.Request.URL.String()).
117-
Int("code", resp.StatusCode).
118-
Str("latency", latency).
119-
Msg("http client response")
113+
respEvt.
114+
Str("method", resp.Request.Method).
115+
Str("url", resp.Request.URL.String()).
116+
Int("code", resp.StatusCode).
117+
Str("latency", latency).
118+
Msg("http client response")
119+
}
120120

121121
return resp, err
122122
}

httpclient/transport/logger_test.go

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,14 +72,14 @@ func TestLoggerTransportRoundTrip(t *testing.T) {
7272

7373
assert.Equal(t, http.StatusNoContent, resp.StatusCode)
7474

75-
logtest.AssertHasLogRecord(t, logBuffer, map[string]interface{}{
75+
logtest.AssertHasNotLogRecord(t, logBuffer, map[string]interface{}{
7676
"level": "info",
7777
"method": "GET",
7878
"url": server.URL,
7979
"message": "http client request",
8080
})
8181

82-
logtest.AssertHasLogRecord(t, logBuffer, map[string]interface{}{
82+
logtest.AssertHasNotLogRecord(t, logBuffer, map[string]interface{}{
8383
"level": "info",
8484
"url": server.URL,
8585
"code": http.StatusNoContent,
@@ -212,6 +212,48 @@ func TestLoggerTransportRoundTripWithConfig(t *testing.T) {
212212
"response": `{"output":"error"}`,
213213
"message": "http client response",
214214
})
215+
216+
// other transport with response level logging
217+
trans2 := transport.NewLoggerTransportWithConfig(nil, &transport.LoggerTransportConfig{
218+
LogRequest: true,
219+
LogResponse: true,
220+
LogRequestBody: true,
221+
LogResponseBody: true,
222+
LogRequestLevel: zerolog.DebugLevel,
223+
LogResponseLevel: zerolog.WarnLevel,
224+
LogResponseLevelFromResponseCode: false,
225+
})
226+
227+
// 404 response
228+
data = []byte(`{"input":"data"}`)
229+
req = httptest.NewRequest(http.MethodPost, server.URL, bytes.NewBuffer(data))
230+
req.Header.Add("expected-response-code", "404")
231+
req.Header.Add("expected-response-body", `{"output":"not found"}`)
232+
req = req.WithContext(logger.WithContext(context.Background()))
233+
234+
resp, err = trans2.RoundTrip(req)
235+
assert.NoError(t, err)
236+
237+
err = resp.Body.Close()
238+
assert.NoError(t, err)
239+
240+
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
241+
242+
logtest.AssertContainLogRecord(t, logBuffer, map[string]interface{}{
243+
"level": "debug",
244+
"method": "POST",
245+
"url": server.URL,
246+
"request": `{"input":"data"}`,
247+
"message": "http client request",
248+
})
249+
250+
logtest.AssertContainLogRecord(t, logBuffer, map[string]interface{}{
251+
"level": "warn",
252+
"url": server.URL,
253+
"code": http.StatusNotFound,
254+
"response": `{"output":"not found"}`,
255+
"message": "http client response",
256+
})
215257
}
216258

217259
func TestLoggerTransportRoundTripWithFailure(t *testing.T) {
@@ -241,7 +283,7 @@ func TestLoggerTransportRoundTripWithFailure(t *testing.T) {
241283
assert.Error(t, err)
242284
assert.Equal(t, "custom http error", err.Error())
243285

244-
logtest.AssertHasLogRecord(t, logBuffer, map[string]interface{}{
286+
logtest.AssertHasNotLogRecord(t, logBuffer, map[string]interface{}{
245287
"level": "info",
246288
"method": "GET",
247289
"url": server.URL,

httpclient/transport/metrics.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ import (
1010
)
1111

1212
const (
13-
HttpClientMetricsRequestsCount = "client_requests_total"
14-
HttpClientMetricsRequestsDuration = "client_requests_duration_seconds"
13+
HttpClientMetricsRequestsCount = "httpclient_requests_total"
14+
HttpClientMetricsRequestsDuration = "httpclient_requests_duration_seconds"
1515
)
1616

1717
// MetricsTransport is a wrapper around [http.RoundTripper] with some [MetricsTransportConfig] configuration.

httpclient/transport/metrics_test.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,17 @@ func TestMetricsTransportRoundTrip(t *testing.T) {
3939
// requests counter assertions
4040
expectedCounterMetric := fmt.Sprintf(
4141
`
42-
# HELP client_requests_total Number of performed HTTP requests
43-
# TYPE client_requests_total counter
44-
client_requests_total{host="%s",method="GET",path="",status="5xx"} 1
42+
# HELP httpclient_requests_total Number of performed HTTP requests
43+
# TYPE httpclient_requests_total counter
44+
httpclient_requests_total{host="%s",method="GET",path="",status="5xx"} 1
4545
`,
4646
server.URL,
4747
)
4848

4949
err = testutil.GatherAndCompare(
5050
prometheus.DefaultGatherer,
5151
strings.NewReader(expectedCounterMetric),
52-
"client_requests_total",
52+
"httpclient_requests_total",
5353
)
5454
assert.NoError(t, err)
5555
}
@@ -107,11 +107,11 @@ func TestMetricsTransportRoundTripWithBaseAndConfig(t *testing.T) {
107107
// requests counter assertions
108108
expectedCounterMetric := fmt.Sprintf(
109109
`
110-
# HELP foo_bar_client_requests_total Number of performed HTTP requests
111-
# TYPE foo_bar_client_requests_total counter
112-
foo_bar_client_requests_total{host="%s",method="GET",path="",status="204"} 1
113-
foo_bar_client_requests_total{host="%s",method="GET",path="/foo/4/baz",status="204"} 1
114-
foo_bar_client_requests_total{host="%s",method="GET",path="/foo/{fooId}/bar?page={pageId}",status="204"} 3
110+
# HELP foo_bar_httpclient_requests_total Number of performed HTTP requests
111+
# TYPE foo_bar_httpclient_requests_total counter
112+
foo_bar_httpclient_requests_total{host="%s",method="GET",path="",status="204"} 1
113+
foo_bar_httpclient_requests_total{host="%s",method="GET",path="/foo/4/baz",status="204"} 1
114+
foo_bar_httpclient_requests_total{host="%s",method="GET",path="/foo/{fooId}/bar?page={pageId}",status="204"} 3
115115
`,
116116
server.URL,
117117
server.URL,
@@ -121,7 +121,7 @@ func TestMetricsTransportRoundTripWithBaseAndConfig(t *testing.T) {
121121
err := testutil.GatherAndCompare(
122122
registry,
123123
strings.NewReader(expectedCounterMetric),
124-
"foo_bar_client_requests_total",
124+
"foo_bar_httpclient_requests_total",
125125
)
126126
assert.NoError(t, err)
127127
}
@@ -161,17 +161,17 @@ func TestMetricsTransportRoundTripWithFailure(t *testing.T) {
161161
// requests counter assertions
162162
expectedCounterMetric := fmt.Sprintf(
163163
`
164-
# HELP foo_bar_client_requests_total Number of performed HTTP requests
165-
# TYPE foo_bar_client_requests_total counter
166-
foo_bar_client_requests_total{host="%s",method="GET",path="",status="error"} 1
164+
# HELP foo_bar_httpclient_requests_total Number of performed HTTP requests
165+
# TYPE foo_bar_httpclient_requests_total counter
166+
foo_bar_httpclient_requests_total{host="%s",method="GET",path="",status="error"} 1
167167
`,
168168
server.URL,
169169
)
170170

171171
err = testutil.GatherAndCompare(
172172
registry,
173173
strings.NewReader(expectedCounterMetric),
174-
"foo_bar_client_requests_total",
174+
"foo_bar_httpclient_requests_total",
175175
)
176176
assert.NoError(t, err)
177177
}

0 commit comments

Comments
 (0)