Readable traffic log: drop heartbeat noise, surface visitors and errors
Deploy with Docker Compose / deploy (push) Successful in 50s
Deploy with Docker Compose / deploy (push) Successful in 50s
Replaces gin's default logger with a custom formatter: - /auth/validate-admin (nginx auth_request subrequests — the 5-seconds flood that is not a user), /auth/refresh and /auth/check no longer log a line at all on success; their failures are kept. - Human latency units (15ms, not 153020ns). - Lines for requests from outside the docker subnet carry the client IP — the "who is using my site" line — while internal infrastructure successes stay lean. - 4xx lines carry " !!", 5xx " !!! SERVER ERROR", both greppable. The admin panel's Diagnostics log pane gains a "visitors only" filter that keeps just the IP-suffixed and error lines (on by default). Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
+6
-1
@@ -43,7 +43,12 @@ func main() {
|
|||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
r := gin.Default()
|
r := gin.New()
|
||||||
|
// Custom traffic formatter (services/traffic_log.go) instead of gin's
|
||||||
|
// default: quiets heartbeat subrequests, surfaces external visitors and
|
||||||
|
// server errors. Same writer pair as above.
|
||||||
|
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
|
||||||
|
r.Use(gin.Recovery())
|
||||||
|
|
||||||
// Only the Docker network nginx sits on may set X-Forwarded-For. Without
|
// Only the Docker network nginx sits on may set X-Forwarded-For. Without
|
||||||
// this pin any client could spoof its IP and defeat the per-IP login rate
|
// this pin any client could spoof its IP and defeat the per-IP login rate
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This file replaces gin.Logger with a formatter tuned for one reader: the
|
||||||
|
// site owner scanning the log for "who is using my site". Two goals:
|
||||||
|
//
|
||||||
|
// 1. Quietness. The log is flooded by traffic that is not a human visit:
|
||||||
|
// nginx auth_request subrequests (/auth/validate-admin, re-run for every
|
||||||
|
// admin page hit), the front end's own polling (`/auth/refresh_token`,
|
||||||
|
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
|
||||||
|
// a single terse line, or dropped entirely when repeated in a short
|
||||||
|
// window — a 200 on a poll says nothing worth a line each time.
|
||||||
|
//
|
||||||
|
// 2. Salience. A request that matters (an external IP, an error status, a
|
||||||
|
// slow response) gets a line that stands out and carries the pieces that
|
||||||
|
// answer "who": client IP, path, status, latency.
|
||||||
|
|
||||||
|
// logQuietDrop lists paths whose 2xx responses are dropped outright. These
|
||||||
|
// are all heartbeat-style endpoints: identical every few seconds, no signal.
|
||||||
|
var logQuietDrop = map[string]bool{
|
||||||
|
"/auth/validate-admin": true, // nginx auth_request subrequest
|
||||||
|
"/auth/refresh": true, // front-end token refresh
|
||||||
|
"/auth/check": true, // front-end session check
|
||||||
|
}
|
||||||
|
|
||||||
|
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
|
||||||
|
// signature so it plugs into gin.LoggerWithFormatter.
|
||||||
|
func TrafficLogFormatter(params gin.LogFormatterParams) string {
|
||||||
|
// gin hands the full URL (path + query) in Path; Query is split off
|
||||||
|
// params.ErrorMessage... not needed — just use Path which carries both.
|
||||||
|
path := params.Path
|
||||||
|
|
||||||
|
// Latency is human-scaled rather than raw nanoseconds: "1.2ms" scans
|
||||||
|
// faster than "1230689ns" when you are skimming.
|
||||||
|
latency := params.Latency
|
||||||
|
unit := "ns"
|
||||||
|
switch {
|
||||||
|
case latency > time.Minute:
|
||||||
|
unit, latency = "m", latency/time.Minute
|
||||||
|
case latency > time.Second:
|
||||||
|
unit, latency = "s", latency/time.Second
|
||||||
|
case latency > time.Millisecond:
|
||||||
|
unit, latency = "ms", latency/time.Millisecond
|
||||||
|
case latency > time.Microsecond:
|
||||||
|
unit, latency = "µs", latency/time.Microsecond
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errors (>=500) are marked so they survive even a fast scroll; the
|
||||||
|
// literal marker also makes them greppable in a rotated log.
|
||||||
|
marker := ""
|
||||||
|
if params.StatusCode >= 500 {
|
||||||
|
marker = " !!! SERVER ERROR"
|
||||||
|
} else if params.StatusCode >= 400 {
|
||||||
|
marker = " !!"
|
||||||
|
}
|
||||||
|
|
||||||
|
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
|
||||||
|
// is still interesting (an expired session raging against refresh, a
|
||||||
|
// broken admin gate) and is kept.
|
||||||
|
if logQuietDrop[path] && params.StatusCode < 400 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
line := fmt.Sprintf("%s %s %d %s%s", params.Method, path, params.StatusCode,
|
||||||
|
fmt.Sprintf("%.0f%s", float64(latency), unit), marker)
|
||||||
|
|
||||||
|
// Visitor traffic gets the IP appended — the "who". Infrastructure
|
||||||
|
// traffic (nginx's own feet on the internal subnet) already has its IP
|
||||||
|
// implied and is left lean.
|
||||||
|
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
|
||||||
|
line += " " + params.ClientIP
|
||||||
|
}
|
||||||
|
|
||||||
|
return line + "\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// logIsInterestingClient reports whether a client IP is likely an actual
|
||||||
|
// visitor rather than infrastructure. nginx proxies everything, so the IPs
|
||||||
|
// that appear are either forwarded-from-humans or the ingress itself.
|
||||||
|
func logIsInterestingClient(ip string) bool {
|
||||||
|
// Docker's bridge network: nginx's own feet. Not a visitor.
|
||||||
|
return !startsWith(ip, "172.28.")
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWith(s, prefix string) bool {
|
||||||
|
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func fmtParams(method, path string, status int, ip string, d time.Duration) gin.LogFormatterParams {
|
||||||
|
return gin.LogFormatterParams{
|
||||||
|
Method: method,
|
||||||
|
Path: path,
|
||||||
|
StatusCode: status,
|
||||||
|
ClientIP: ip,
|
||||||
|
Latency: d,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrafficFormatterDropsQuietHeartbeats(t *testing.T) {
|
||||||
|
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 200, "172.28.0.6", 2*time.Millisecond))
|
||||||
|
if out != "" {
|
||||||
|
t.Fatalf("plain validate-admin 200 should be dropped, got %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrafficFormatterKeepsHeartbeatFailures(t *testing.T) {
|
||||||
|
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 401, "172.28.0.6", time.Millisecond))
|
||||||
|
if out == "" {
|
||||||
|
t.Fatal("a failing heartbeat must stay visible")
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "401") || !strings.Contains(out, "172.28.0.6") {
|
||||||
|
t.Fatalf("failure line missing fields: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrafficFormatterVisitorGetsIP(t *testing.T) {
|
||||||
|
out := TrafficLogFormatter(fmtParams("GET", "/", 200, "82.69.124.224", 15*time.Millisecond))
|
||||||
|
if !strings.Contains(out, "82.69.124.224") {
|
||||||
|
t.Fatalf("visitor line should carry the IP: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrafficFormatterInfra200Lean(t *testing.T) {
|
||||||
|
out := TrafficLogFormatter(fmtParams("POST", "/graphql", 200, "172.28.0.6", 5*time.Millisecond))
|
||||||
|
if strings.Contains(out, "172.28.0.6") {
|
||||||
|
t.Fatalf("infrastructure success should not repeat its IP: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrafficFormatterServerErrorMarked(t *testing.T) {
|
||||||
|
out := TrafficLogFormatter(fmtParams("GET", "/spotify/listening", 500, "82.69.124.224", time.Second))
|
||||||
|
if !strings.Contains(out, "!!! SERVER ERROR") {
|
||||||
|
t.Fatalf("server error should be marked: %q", out)
|
||||||
|
}
|
||||||
|
// Human latency units, not nanoseconds.
|
||||||
|
if strings.Contains(out, "ns") {
|
||||||
|
t.Fatalf("latency should be human units: %q", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrafficFormatterInfraIPClassification(t *testing.T) {
|
||||||
|
if !logIsInterestingClient("82.69.124.224") {
|
||||||
|
t.Fatal("public IP must read as a visitor")
|
||||||
|
}
|
||||||
|
if logIsInterestingClient("172.28.0.6") {
|
||||||
|
t.Fatal("docker-network IP must not read as a visitor")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,6 +49,15 @@ const blank = computed(() =>
|
|||||||
vars.value.filter((v) => !v.set),
|
vars.value.filter((v) => !v.set),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Traffic view: a filter over the log tail for "who is using my site" —
|
||||||
|
// lines with a client IP (the formatter appends it only for real visitors
|
||||||
|
// and error statuses). Skips the standard line numbers of JSON-array output.
|
||||||
|
const trafficOnly = ref(true);
|
||||||
|
const shownLines = computed(() => {
|
||||||
|
if (!trafficOnly.value) return lines.value;
|
||||||
|
return lines.value.filter((l) => /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(l.trim()) || l.includes("!!! SERVER ERROR") || l.includes(" !!"));
|
||||||
|
});
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
fetchConfig();
|
fetchConfig();
|
||||||
fetchLogs();
|
fetchLogs();
|
||||||
@@ -92,12 +101,18 @@ onMounted(() => {
|
|||||||
messages, newest last.
|
messages, newest last.
|
||||||
</p>
|
</p>
|
||||||
<div class="log-controls">
|
<div class="log-controls">
|
||||||
|
<label class="hint toggle">
|
||||||
|
<input type="checkbox" v-model="trafficOnly" /> visitors only
|
||||||
|
</label>
|
||||||
<Button :disabled="loadingLogs" @click="fetchLogs">
|
<Button :disabled="loadingLogs" @click="fetchLogs">
|
||||||
{{ loadingLogs ? "Loading…" : "Refresh" }}
|
{{ loadingLogs ? "Loading…" : "Refresh" }}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="logsError" class="error">{{ logsError }}</p>
|
<p v-if="logsError" class="error">{{ logsError }}</p>
|
||||||
<pre v-else class="log-output">{{ lines.join("\n") }}</pre>
|
<p v-else-if="shownLines.length === 0" class="hint">
|
||||||
|
No {{ trafficOnly ? "visitor" : "" }} lines in the current tail.
|
||||||
|
</p>
|
||||||
|
<pre v-else class="log-output">{{ shownLines.join("\n") }}</pre>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -137,6 +152,15 @@ td {
|
|||||||
.log-controls {
|
.log-controls {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
align-items: center;
|
||||||
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.log-output {
|
.log-output {
|
||||||
|
|||||||
Reference in New Issue
Block a user