Skip to content

Commit

Permalink
Ensure the httplog.Options from httplog.Logger are present in middlew…
Browse files Browse the repository at this point in the history
…are.LogEntry

This fixes go-chi#35 as the httplog.Options#JSON now causes the log entry to
not be pretty printed to stderr if set to true.
  • Loading branch information
stefansaasen committed Feb 13, 2024
1 parent 4a0d794 commit 4d696fb
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion httplog.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ type requestLogger struct {
}

func (l *requestLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
entry := &RequestLoggerEntry{}
entry := &RequestLoggerEntry{Options: l.Options}
msg := fmt.Sprintf("Request: %s %s", r.Method, r.URL.Path)

if l.Options.RequestHeaders {
Expand Down
46 changes: 46 additions & 0 deletions httplog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package httplog

import (
"log/slog"
"net/http"
"net/http/httptest"
"reflect"
"testing"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)

// Test that ensures the Logger options match the options of a LogEntry
func Test_requestLogger_NewLogEntry_Options(t *testing.T) {
opts := Options{
Concise: true,
JSON: true,
}
logger := &Logger{
Logger: slog.Default(),
Options: opts,
}

r := chi.NewMux()
r.Use(Handler(logger))

var entryFromRequest middleware.LogEntry
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
entryFromRequest = middleware.GetLogEntry(r)
w.Write([]byte("OK"))
})

req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()

r.ServeHTTP(w, req)

rEntry, ok := entryFromRequest.(*RequestLoggerEntry)
if !ok {
t.Errorf("expected log entry to be a RequestLoggerEntry")
}
if !reflect.DeepEqual(opts, rEntry.Options) {
t.Errorf("entry = %v, want %v", entryFromRequest, opts)
}
}

0 comments on commit 4d696fb

Please sign in to comment.