Skip to content

Commit 4132a50

Browse files
Fix server.address field in HTTP logs (#4142)
* Fix server.address field in HTTP logs, fix request log condition
1 parent ac677ae commit 4132a50

File tree

3 files changed

+70
-16
lines changed

3 files changed

+70
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Kind can be one of:
2+
# - breaking-change: a change to previously-documented behavior
3+
# - deprecation: functionality that is being removed in a later release
4+
# - bug-fix: fixes a problem in a previous version
5+
# - enhancement: extends functionality but does not break or fix existing behavior
6+
# - feature: new functionality
7+
# - known-issue: problems that we are aware of in a given version
8+
# - security: impacts on the security of a product or a user’s deployment.
9+
# - upgrade: important information for someone upgrading from a prior version
10+
# - other: does not fit into any of the other categories
11+
kind: bug-fix
12+
13+
# Change summary; a 80ish characters long description of the change.
14+
summary: Fix server.address field in HTTP logs
15+
16+
# Long description; in case the summary is not enough to describe the change
17+
# this field accommodate a description without length limits.
18+
# NOTE: This field will be rendered only for breaking-change and known-issue kinds at the moment.
19+
#description:
20+
21+
# Affected component; usually one of "elastic-agent", "fleet-server", "filebeat", "metricbeat", "auditbeat", "all", etc.
22+
component: fleet-server
23+
24+
# PR URL; optional; the PR number that added the changeset.
25+
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added.
26+
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number.
27+
# Please provide it if you are adding a fragment for a different PR.
28+
#pr: https://github.com/owner/repo/1234
29+
30+
# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of).
31+
# If not present is automatically filled by the tooling with the issue linked to the PR number.
32+
#issue: https://github.com/owner/repo/1234

internal/pkg/logger/http.go

+8-4
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,11 @@ func Middleware(next http.Handler) http.Handler {
216216
w.Header().Set(HeaderRequestID, reqID)
217217

218218
// get the server bound addr from the req ctx
219-
addr, _ := r.Context().Value(http.LocalAddrContextKey).(string)
219+
var addr string
220+
netAddr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
221+
if ok {
222+
addr = netAddr.String()
223+
}
220224

221225
// Add trace correlation fields
222226
ctx := r.Context()
@@ -250,13 +254,13 @@ func Middleware(next http.Handler) http.Handler {
250254
next.ServeHTTP(wrCounter, r)
251255
httpMeta(r, e)
252256

253-
if zlog.Debug().Enabled() || (wrCounter.statusCode < 200 && wrCounter.statusCode >= 300) {
257+
// Write an info level log line for each HTTP request if debug is enabled, or a non-2XX status is returned.
258+
if zlog.Debug().Enabled() || (wrCounter.statusCode < 200 || wrCounter.statusCode >= 300) {
254259
e.Uint64(ECSHTTPRequestBodyBytes, rdCounter.Count())
255260
e.Uint64(ECSHTTPResponseBodyBytes, wrCounter.Count())
256261
e.Int(ECSHTTPResponseCode, wrCounter.statusCode)
257262
e.Int64(ECSEventDuration, time.Since(start).Nanoseconds())
258-
259-
e.Msgf("%d HTTP Request", wrCounter.statusCode)
263+
e.Msg("HTTP Request")
260264
}
261265
}
262266
return http.HandlerFunc(fn)

internal/pkg/logger/http_test.go

+30-12
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,55 @@
55
package logger
66

77
import (
8+
"bytes"
89
"context"
10+
"encoding/json"
11+
"net"
912
"net/http"
1013
"net/http/httptest"
1114
"testing"
1215
"time"
1316

17+
"github.com/rs/zerolog"
1418
"github.com/stretchr/testify/require"
15-
16-
testlog "github.com/elastic/fleet-server/v7/internal/pkg/testing/log"
1719
)
1820

1921
func TestMiddleware(t *testing.T) {
20-
ctx := testlog.SetLogger(t).WithContext(context.Background())
2122
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2223
ts, ok := CtxStartTime(r.Context())
2324
require.True(t, ok, "expected context to have start time")
2425
require.False(t, ts.Equal(time.Time{}), "expected start time to be non-zero")
2526

26-
w.WriteHeader(http.StatusOK)
27+
w.WriteHeader(http.StatusBadRequest)
2728
_, _ = w.Write([]byte(`hello, world`))
2829
})
2930

30-
w := httptest.NewRecorder()
31-
req := httptest.NewRequest("GET", "/", nil).WithContext(ctx)
32-
33-
Middleware(h).ServeHTTP(w, req)
34-
res := w.Result()
31+
var b bytes.Buffer
32+
logger := zerolog.New(&b).Level(zerolog.InfoLevel)
33+
ctx := logger.WithContext(context.Background())
34+
35+
srv := httptest.NewUnstartedServer(Middleware(h))
36+
srv.Config.BaseContext = func(_ net.Listener) context.Context {
37+
return ctx
38+
}
39+
srv.Start()
40+
defer srv.Close()
41+
reqCtx, cancel := context.WithCancel(context.Background())
42+
defer cancel()
43+
req, err := http.NewRequestWithContext(reqCtx, "GET", srv.URL, nil)
44+
require.NoError(t, err)
45+
46+
res, err := srv.Client().Do(req)
47+
require.NoError(t, err)
3548
res.Body.Close()
36-
require.Equal(t, http.StatusOK, res.StatusCode)
49+
require.Equal(t, http.StatusBadRequest, res.StatusCode)
3750
_, ok := res.Header[HeaderRequestID]
3851
require.True(t, ok, "expected to have a request ID")
39-
reqID := req.Header.Get(HeaderRequestID)
40-
require.NotEmpty(t, reqID)
52+
53+
var obj map[string]any
54+
err = json.Unmarshal(b.Bytes(), &obj)
55+
require.NoError(t, err)
56+
v, ok := obj[ECSServerAddress]
57+
require.Truef(t, ok, "expected to find key: %s in %v", ECSServerAddress, obj)
58+
require.NotEmpty(t, v)
4159
}

0 commit comments

Comments
 (0)