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
7 changes: 3 additions & 4 deletions json_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"io"
"log"
"net/http"
"os"
"strings"
"time"
)
Expand All @@ -25,9 +24,9 @@ type JSONLogger struct {
// JSONLogged returns an http.Handler that logs requests and responses in a parse-able json line.
// complete with paths, statuses, headers, and bodies. Sensitive information may be
// redacted by a user-defined function.
func JSONLogged(handler http.Handler, redactor Redactor) *JSONLogger {
func JSONLogged(handler http.Handler, redactor Redactor, logger *log.Logger) *JSONLogger {
return &JSONLogger{
logger: log.New(os.Stdout, "", 0),
logger: logger,
handler: handler,
redactor: redactor,
RequestIDCreator: requestIDCreator,
Expand Down Expand Up @@ -79,7 +78,7 @@ func (jl *JSONLogger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if nil != jl.redactor {
s = jl.redactor(s)
}
jl.logger.Print("@json:", s)
jl.logger.Print(s)
}

func jsonLogHTTPHeader(h http.Header) map[string]string {
Expand Down
16 changes: 9 additions & 7 deletions json_logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,22 @@ func TestJSONLogger(t *testing.T) {
r.Header.Set("Accept", "application/json")
r.Header.Set("Content-Type", "application/json")

b := &bytes.Buffer{}
customLogger := log.New(b, "", 0)

logger := JSONLogged(Marshaled(func(u *url.URL, h http.Header, rq *testRequest) (int, http.Header, *testResponse, error) {
return http.StatusOK, nil, &testResponse{"bar"}, nil
}), nil)
}), nil, customLogger)

logger.RequestIDCreator = func(r *http.Request) RequestID {
return "request-id"
}

b := &bytes.Buffer{}
logger.logger = log.New(b, "", 0)
logger.ServeHTTP(w, r)

var m jsonLog

err := json.Unmarshal(b.Bytes()[6:], &m)
err := json.Unmarshal(b.Bytes(), &m)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -78,14 +79,15 @@ func TestJSONLoggerRedactor(t *testing.T) {
r, _ := http.NewRequest("GET", "http://example.com/foo", nil)
r.Header.Set("Accept", "application/json")

b := &bytes.Buffer{}
customLogger := log.New(b, "", 0)

logger := JSONLogged(Marshaled(func(u *url.URL, h http.Header, rq *testRequest) (int, http.Header, *testResponse, error) {
return http.StatusOK, nil, &testResponse{"SECRET"}, nil
}), func(s string) string {
return strings.Replace(s, "SECRET", "REDACTED", -1)
})
}, customLogger)

b := &bytes.Buffer{}
logger.logger = log.New(b, "", 0)
logger.ServeHTTP(w, r)
s := b.String()

Expand Down