Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
chore(logging): better log format
Browse files Browse the repository at this point in the history
Co-authored-by: Paul B. Beskow <[email protected]>
  • Loading branch information
erikvatt and paulbes committed Aug 8, 2024
1 parent 700439a commit 8c0807f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
8 changes: 3 additions & 5 deletions pkg/requestlogger/requestlogger.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package requestlogger

import (
"fmt"
"net/http"
"strconv"
"time"
Expand Down Expand Up @@ -41,11 +42,8 @@ func Middleware(log zerolog.Logger, pathFilters ...string) func(next http.Handle

log.Info().Timestamp().Fields(map[string]interface{}{
"request_id": requestID,
"method": r.Method,
"url": r.URL.Path,
"status": ww.Status(),
"browser": ua.Name,
"os": ua.OS,
"request": fmt.Sprintf("%v %v (response_code: %v)", r.Method, r.URL.Path, ww.Status()),
"browser": fmt.Sprintf("%v (%v)", ua.Name, ua.OS),
"bytes_in": bytesIn,
"bytes_out": ww.BytesWritten(),
"latency_ms": float64(t2.Sub(t1).Nanoseconds()) / 1000000.0, //nolint: gomnd
Expand Down
15 changes: 6 additions & 9 deletions pkg/requestlogger/requestlogger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package requestlogger_test

import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -26,12 +27,9 @@ type LogFormat struct {
BytesIn int `json:"bytes_in"`
BytesOut int `json:"bytes_out"`
Latency float64 `json:"latency_ms"`
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status"`
Request string `json:"request"`
Message string `json:"message"`
Browser string `json:"browser"`
OS string `json:"os"`
}

func TestLoggerMiddleware(t *testing.T) {
Expand All @@ -54,12 +52,9 @@ func TestLoggerMiddleware(t *testing.T) {
Level: "info",
BytesIn: 0,
BytesOut: 2,
Method: http.MethodGet,
URL: "/foo",
Status: http.StatusOK,
Request: "GET /foo (response_code: 200)",
Message: "incoming_request",
Browser: "Chrome",
OS: "Windows",
Browser: "Chrome (Windows)",
},
},
{
Expand Down Expand Up @@ -100,6 +95,8 @@ func TestLoggerMiddleware(t *testing.T) {
err := json.Unmarshal(buf.Bytes(), got)
require.NoError(t, err)

fmt.Println(buf.String())

diff := cmp.Diff(tc.expect, got, cmpopts.IgnoreFields(LogFormat{}, "Time", "Latency", "RequestID"))
assert.Empty(t, diff)
assert.Greater(t, got.Latency, 0.0)
Expand Down

0 comments on commit 8c0807f

Please sign in to comment.