Skip to content
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
5 changes: 5 additions & 0 deletions middleware/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package middleware

import (
"bufio"
"context"
"io"
"log/slog"
"net"
Expand Down Expand Up @@ -131,6 +132,10 @@ func (l *lm) Log(next http.Handler, accessLogs bool) http.Handler {
}

func (l *lm) writeLog(accessLog bool, r *http.Request, bw *wrapper, start time.Time) {
if !l.log.Enabled(context.Background(), slog.LevelInfo) {
return
}

if !accessLog {
l.log.Info("http log",
"status", bw.code,
Expand Down
41 changes: 41 additions & 0 deletions middleware/log_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package middleware

import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -110,3 +115,39 @@ func TestWrapper_ResetClearsState(t *testing.T) {
assert.Zero(t, w.read)
assert.Zero(t, w.write)
}

func TestWriteLog_BuildsNothingWhenLevelDisabled(t *testing.T) {
l := &lm{log: slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
Level: slog.LevelError,
}))}

bw := &wrapper{code: http.StatusOK}
req := httptest.NewRequest(http.MethodGet, "/some/path?a=1&b=2", nil)
req.Header.Set("User-Agent", "test-agent/1.0")
req.Header.Set("Referer", "http://example.com/from")
start := time.Now()

access := testing.AllocsPerRun(100, func() {
l.writeLog(true, req, bw, start)
})
assert.Zero(t, access, "a discarded access-log line must allocate nothing")

plain := testing.AllocsPerRun(100, func() {
l.writeLog(false, req, bw, start)
})
assert.Zero(t, plain, "a discarded log line must allocate nothing")
}

func TestWriteLog_EmittedWhenLevelEnabled(t *testing.T) {
var buf bytes.Buffer
l := &lm{log: slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo}))}

bw := &wrapper{code: http.StatusOK, read: 3, write: 7}
req := httptest.NewRequest(http.MethodGet, "/some/path", nil)

l.writeLog(false, req, bw, time.Now())

assert.Contains(t, buf.String(), "http log")
assert.Contains(t, buf.String(), "read_bytes=3")
assert.Contains(t, buf.String(), "write_bytes=7")
}