Log request bodies at nginx and view logs in Dozzle
Test and deploy / deploy (push) Has been cancelled
Test and deploy / test (push) Has been cancelled

nginx writes one JSON line per request, body included, to
logs/nginx/payloads.log (nginx/payload_log.conf). Bodies mentioning a
password, token or secret are logged as [redacted]. A `traffic` container
tails the file so it shows up as its own stream in Dozzle, which is served
at /dozzle/ behind the admin auth_request.

Dozzle replaces the admin panel's Diagnostics tab, so that tab and the
/admin/logs endpoint behind it are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-15 15:46:26 +01:00
co-authored by Claude Opus 5.5
parent 604ac32028
commit 58880a4e07
16 changed files with 182 additions and 289 deletions
+1 -1
View File
@@ -62,7 +62,7 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`. **Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. **Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view.
## Backend Structure ## Backend Structure
+37 -1
View File
@@ -65,6 +65,8 @@ backend icecast2 gitea sb sb-pub python | |
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no | | vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
| certbot | `certbot` | — | — | no | | certbot | `certbot` | — | — | no |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) | | cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
Container names come from `.env`, and nginx builds its upstreams from the same Container names come from `.env`, and nginx builds its upstreams from the same
variables. **Renaming a `*_HOST` value renames the container and repoints nginx variables. **Renaming a `*_HOST` value renames the container and repoints nginx
@@ -333,7 +335,7 @@ of deleting the directory:
| `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. | | `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data | | `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea | | `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs | | | `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") |
| `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git | | `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git |
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public | | `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
@@ -467,6 +469,40 @@ docker compose ps # note: `vue` Exited(0) is correct
docker compose logs certbot # issuance / renewal outcomes docker compose logs certbot # issuance / renewal outcomes
``` ```
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
login required).
**Incoming request bodies.** nginx writes one JSON line per request, body
included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The
`traffic` container tails it, so in Dozzle pick **traffic** and each request
renders as fields you can search. From a shell:
```
tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")'
jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log
```
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
(that covers every login and the refresh call). Bodies over 64 KB, i.e.
uploads, are logged with an empty `body`, and responses are never logged.
The file is never rotated by the stack. On the Pi, add
`/etc/logrotate.d/web_server`:
```
/home/<user>/web_server/logs/nginx/*.log {
weekly
rotate 4
compress
missingok
notifempty
copytruncate
}
```
`copytruncate` because nginx keeps the file open; `tail -F` in `traffic`
follows the truncation.
**Reset the database** — destructive; wipes the app database **and Gitea's**: **Reset the database** — destructive; wipes the app database **and Gitea's**:
``` ```
-1
View File
@@ -176,7 +176,6 @@ for the things GraphQL cannot do:
| `/notes/*path` | streams a file download, not JSON | | `/notes/*path` | streams a file download, not JSON |
| `/ws` | WebSocket upgrade | | `/ws` | WebSocket upgrade |
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working | | `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
| `/admin/logs` | files on disk, not the data model |
## Calling the Python service ## Calling the Python service
-92
View File
@@ -1,92 +0,0 @@
package handlers
import (
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
)
// This file backs the admin diagnostics panel's log tail. It is an admin-only
// REST endpoint rather than GraphQL because it reads the filesystem — outside
// the data model the GraphQL schema describes.
// logTailBytes and logTailLines bound how much of the log file one request
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
// cheap even on the Pi.
const (
logTailBytes = 256 << 10
logTailLines = 500
)
// Logs backs GET /admin/logs. It returns the tail of the backend's own log
// file (go.log — Gin traffic plus application log lines), which lives on the
// bind-mounted ./logs volume.
//
// Why tail and not offer a range: the panel wants "what happened recently",
// and the file can grow unboundedly between rotations, so anything else
// invites reading the whole thing into memory.
func (store *Store) Logs(ctx *gin.Context) {
lines, size, err := tailLogFile(logPath)
if err != nil {
// The mount being absent is a deployment problem worth surfacing
// distinctly from "log file empty".
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size})
}
// logPath matches the file main.go opens for gin.DefaultWriter.
const logPath = "/backend/logs/go.log"
// tailLogFile returns the last logTailLines lines of a file, reading at most
// logTailBytes from the end. Split out from the handler so the offset and
// partial-line rules are testable without a filesystem mount.
func tailLogFile(path string) ([]string, int64, error) {
f, err := os.Open(path)
if err != nil {
return nil, 0, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, 0, err
}
// Read from near the end rather than head-to-toe so the read stays
// constant-size regardless of how old the file is.
start := int64(0)
if info.Size() > logTailBytes {
start = info.Size() - logTailBytes
}
buf := make([]byte, info.Size()-start)
if len(buf) > 0 {
if _, err := f.ReadAt(buf, start); err != nil {
return nil, 0, err
}
}
// Starting mid-file almost certainly lands mid-line; drop that fragment
// so the panel never renders a truncated first entry.
text := string(buf)
if start > 0 {
if i := strings.IndexByte(text, '\n'); i >= 0 {
text = text[i+1:]
}
}
text = strings.TrimRight(text, "\n")
if text == "" {
return []string{}, info.Size(), nil
}
lines := strings.Split(text, "\n")
if len(lines) > logTailLines {
lines = lines[len(lines)-logTailLines:]
}
return lines, info.Size(), nil
}
-76
View File
@@ -1,76 +0,0 @@
package handlers
import (
"os"
"path/filepath"
"strings"
"testing"
)
// tailLogFile's rules that are easy to get wrong: the line cap, and dropping
// the partial first line when the read started mid-file.
func writeLog(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "go.log")
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("writing fixture: %v", err)
}
return path
}
func TestTailLogFileCapsLines(t *testing.T) {
var b strings.Builder
for range logTailLines + 50 {
b.WriteString("line\n")
}
lines, _, err := tailLogFile(writeLog(t, b.String()))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) != logTailLines {
t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines)
}
}
func TestTailLogFileDropsPartialFirstLine(t *testing.T) {
// A file larger than the byte window: the read starts mid-file, so the
// first line it sees is a fragment and must be discarded.
filler := strings.Repeat("x", 100) + "\n"
var b strings.Builder
for b.Len() < logTailBytes+len(filler) {
b.WriteString(filler)
}
b.WriteString("FINAL\n")
lines, _, err := tailLogFile(writeLog(t, b.String()))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) == 0 {
t.Fatal("expected some lines")
}
if lines[len(lines)-1] != "FINAL" {
t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1])
}
// Every surviving line must be whole, i.e. a full filler line.
if got := lines[0]; got != strings.TrimSuffix(filler, "\n") {
t.Fatalf("first line = %q, want a complete filler line", got)
}
}
func TestTailLogFileEmpty(t *testing.T) {
lines, size, err := tailLogFile(writeLog(t, ""))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) != 0 || size != 0 {
t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size)
}
}
func TestTailLogFileMissing(t *testing.T) {
if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil {
t.Fatal("expected an error for a missing log file")
}
}
-3
View File
@@ -178,9 +178,6 @@ func main() {
// NOTES // NOTES
admin.GET("/notes/*path", store.GetNoteFile) admin.GET("/notes/*path", store.GetNoteFile)
// ADMIN DIAGNOSTICS: log tail for the admin panel.
admin.GET("/admin/logs", store.Logs)
// GRAPHQL // GRAPHQL
// GraphQL is assembled by hand rather than with handler.NewDefaultServer // GraphQL is assembled by hand rather than with handler.NewDefaultServer
// so the transports and extensions below are explicit. // so the transports and extensions below are explicit.
+39
View File
@@ -117,6 +117,7 @@ services:
- python - python
- jobs - jobs
- activity-tracker - activity-tracker
- dozzle
networks: networks:
app-network: app-network:
# The site's public names, resolving to this container for everything # The site's public names, resolving to this container for everything
@@ -142,6 +143,10 @@ services:
- uploads:/uploads - uploads:/uploads
# The SPA written by the one-shot `vue` container. # The SPA written by the one-shot `vue` container.
- vue_dist:/etc/nginx/html - vue_dist:/etc/nginx/html
# The JSON request-body log (nginx/payload_log.conf), kept on the host so
# it survives rebuilds and the `traffic` container can tail it. Grows
# without bound unless rotated — see DEPLOYMENT.md.
- ./logs/nginx:/var/log/nginx/payloads
# Obtains the cert once, then renews every 12h forever. Disabled in dev via # Obtains the cert once, then renews every 12h forever. Disabled in dev via
# the `disabled` profile in docker-compose.dev.yml. Note this is the stock # the `disabled` profile in docker-compose.dev.yml. Note this is the stock
@@ -576,6 +581,40 @@ services:
- TRACKER_TZ=${TRACKER_TZ:-} - TRACKER_TZ=${TRACKER_TZ:-}
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin - AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
# Echoes nginx's JSON request-body log to its own stdout, and does nothing
# else. It exists so Dozzle shows the payloads as a stream of their own,
# rendered as JSON fields, instead of interleaved with nginx's compact access
# log and error output. -F re-opens the file after rotation; -n0 skips the
# backlog on restart, which stays in the file on the host.
traffic:
image: busybox:1.37.0
container_name: traffic
restart: always
command: ["tail", "-n0", "-F", "/logs/payloads.log"]
network_mode: none
volumes:
- ./logs/nginx:/logs:ro
# Dozzle: a live, searchable web view of every container's logs, served at
# /dozzle/ behind the admin login (nginx/nginx_routes.conf.template). The
# `traffic` container is the one to watch for incoming request bodies.
#
# The Docker socket is mounted :ro, but that only stops the file being
# replaced — the API behind it is still fully usable, which is effectively
# root on the Pi. Hence: no published port, the admin auth_request in front,
# and container actions and shell left at their default of off.
dozzle:
image: amir20/dozzle:v11.2.0
container_name: dozzle
restart: always
networks:
- app-network
environment:
- DOZZLE_BASE=/dozzle
- DOZZLE_NO_ANALYTICS=true
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI # Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to # server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
# main, executed by the act_runner that lives outside docker (gitea-runner/). # main, executed by the act_runner that lives outside docker (gitea-runner/).
+7 -1
View File
@@ -1,6 +1,6 @@
# ============================================================================= # =============================================================================
# nginx image — the public edge. Stock nginx plus two tools, three config # nginx image — the public edge. Stock nginx plus two tools, three config
# templates and the two partials they include. # templates, the two partials they include and two static includes.
# #
# BASE: nginx:1.27, pinned to a minor version. Official nginx images are # BASE: nginx:1.27, pinned to a minor version. Official nginx images are
# multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi # multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi
@@ -44,5 +44,11 @@ COPY nginx_routes.conf.template /etc/nginx/nginx_routes.conf.template
# Static security-header include, referenced from nginx.conf.template (and # Static security-header include, referenced from nginx.conf.template (and
# any location that sets its own add_header). Not templated — no envsubst. # any location that sets its own add_header). Not templated — no envsubst.
COPY security_headers.conf /etc/nginx/security_headers.conf COPY security_headers.conf /etc/nginx/security_headers.conf
# Static http-level include for the JSON request-body log (both configs). Not
# templated: its $request_body etc. are nginx variables, not env vars.
COPY payload_log.conf /etc/nginx/payload_log.conf
# The payload log's directory. Normally a bind mount (./logs/nginx); created
# here so nginx still starts when run without it.
RUN mkdir -p /var/log/nginx/payloads
COPY entrypoint.sh /entrypoint.sh COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"] ENTRYPOINT ["/entrypoint.sh"]
+3
View File
@@ -138,6 +138,9 @@ http {
access_log /var/log/nginx/access.log compact; access_log /var/log/nginx/access.log compact;
# JSON request-body log for Dozzle; see payload_log.conf.
include /etc/nginx/payload_log.conf;
# nginx's bundled mime.types has no entry for .mjs, so ES modules would be # nginx's bundled mime.types has no entry for .mjs, so ES modules would be
# served as application/octet-stream and browsers refuse to execute them. # served as application/octet-stream and browsers refuse to execute them.
# This adds the missing mapping without editing the shipped mime.types. # This adds the missing mapping without editing the shipped mime.types.
+3
View File
@@ -62,6 +62,9 @@ http {
access_log /var/log/nginx/access.log compact; access_log /var/log/nginx/access.log compact;
# JSON request-body log for Dozzle; see payload_log.conf.
include /etc/nginx/payload_log.conf;
types { types {
text/javascript mjs; text/javascript mjs;
} }
+25
View File
@@ -81,6 +81,8 @@
set $upstream_tracker http://activity-tracker:8080; set $upstream_tracker http://activity-tracker:8080;
# And the USACO site's. # And the USACO site's.
set $upstream_usaco http://usaco:8080; set $upstream_usaco http://usaco:8080;
# And the Dozzle log viewer's.
set $upstream_dozzle http://dozzle:8080;
# ---- Backend API ----------------------------------------------------- # ---- Backend API -----------------------------------------------------
# Two patterns repeat through every proxied location below: # Two patterns repeat through every proxied location below:
@@ -174,6 +176,29 @@
return 301 /radio/; return 301 /radio/;
} }
# Dozzle: live view of every container's logs, including the `traffic`
# container's JSON request-body log (see payload_log.conf). It reads
# the Docker socket, so it sits behind the same admin `auth_request`
# as /radio/admin/. No prefix-strip rewrite: DOZZLE_BASE=/dozzle makes
# it serve under the prefix itself. Buffering is off and the read
# timeout long because log tails stream over server-sent events.
location = /dozzle {
return 301 /dozzle/;
}
location /dozzle/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
proxy_pass $upstream_dozzle;
proxy_http_version 1.1;
proxy_buffering off;
proxy_read_timeout 1h;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# The icecast ADMIN UI (/radio/admin/*) is a full station-control # The icecast ADMIN UI (/radio/admin/*) is a full station-control
# surface — kick sources, change metadata — protected only by the # surface — kick sources, change metadata — protected only by the
# icecast admin password, and it was reachable from the public # icecast admin password, and it was reachable from the public
+55
View File
@@ -0,0 +1,55 @@
# =============================================================================
# Payload log: one JSON line per request, body included, for inspecting what
# actually arrives at the edge. Included at http level by BOTH nginx.conf and
# nginx_dev.conf, so it is plain nginx (no envsubst) like security_headers.conf.
#
# WHERE IT GOES
# /var/log/nginx/payloads/ is bind-mounted from ./logs/nginx on the host.
# The `traffic` container tails the file to its stdout so Dozzle (/dozzle/)
# shows it as its own clean stream of JSON. The `compact` access log is
# untouched and still goes to the container's stdout.
#
# WHAT IS NOT CAPTURED
# - Bodies larger than client_body_buffer_size: nginx spools those to a
# temp file and leaves $request_body empty. Uploads therefore log with an
# empty body (their size is still in `len`).
# - Bodies of requests nginx answers itself (redirects, static files): it
# never reads them, so $request_body is empty there too.
# - Responses. nginx cannot log a proxied response body.
# - auth_request subrequests: log_subrequest is off by default.
# =============================================================================
# 64k keeps ordinary JSON/GraphQL bodies in memory (the default is 16k on
# 64-bit), which is the only case where $request_body is filled. It is a
# per-request buffer only allocated when a body arrives, so the cost is small.
client_body_buffer_size 64k;
# Redaction: any body mentioning a password, token or secret is logged as a
# placeholder rather than having the field stripped, because nginx has no JSON
# parser. That catches /auth/login, the GraphQL login and change-password
# mutations and the refresh-token call in one rule. Over-matching (a query that
# merely selects a field named *token*) costs a hidden body, never a leak.
# map is evaluated lazily at log time, after the body has been read.
map $request_body $logged_body {
"~*(password|token|secret)" "[redacted]";
default $request_body;
}
# escape=json makes each line valid JSON (quotes, newlines and control bytes
# in the body are escaped), so Dozzle renders it as fields and `jq` reads it.
log_format payloads escape=json '{'
'"time":"$time_iso8601",'
'"ip":"$remote_addr",'
'"method":"$request_method",'
'"host":"$host",'
'"uri":"$request_uri",'
'"status":"$status",'
'"rt":"$request_time",'
'"ctype":"$content_type",'
'"len":"$content_length",'
'"referer":"$http_referer",'
'"ua":"$http_user_agent",'
'"body":"$logged_body"'
'}';
access_log /var/log/nginx/payloads/payloads.log payloads;
+1 -1
View File
@@ -125,7 +125,7 @@ the Vite proxy in dev).
The backend's REST routes go through `src/api.js`, the same idea for plain JSON: The backend's REST routes go through `src/api.js`, the same idea for plain JSON:
```js ```js
const body = await api.get("/admin/logs", { fallback: "Failed to load logs" }); const songs = await api.get("/radio/songs", { fallback: "Failed to load songs" });
await api.post("/radio/upload", formData, { fallback: "Upload failed" }); await api.post("/radio/upload", formData, { fallback: "Upload failed" });
``` ```
+1 -1
View File
@@ -4,7 +4,7 @@
* OAuth starts — everything backend/README.md lists as "not GraphQL"). * OAuth starts — everything backend/README.md lists as "not GraphQL").
* *
* It does two things a bare axios call does not: * It does two things a bare axios call does not:
* - prefixes `/api`, so callers name the route (`api.get("/admin/logs")`); * - prefixes `/api`, so callers name the route (`api.get("/radio/songs")`);
* - turns a failure into an ApiError whose `message` is the backend's * - turns a failure into an ApiError whose `message` is the backend's
* `{"error": "..."}` body when there is one. Every handler reports errors * `{"error": "..."}` body when there is one. Every handler reports errors
* in that shape, and each view used to dig it out of `err.response` itself. * in that shape, and each view used to dig it out of `err.response` itself.
+10 -2
View File
@@ -19,7 +19,6 @@ import CreatePlace from "./CreatePlace.vue";
import ManagePages from "./ManagePages.vue"; import ManagePages from "./ManagePages.vue";
import ManageUsers from "./ManageUsers.vue"; import ManageUsers from "./ManageUsers.vue";
import ManageRadio from "./ManageRadio.vue"; import ManageRadio from "./ManageRadio.vue";
import Diagnostics from "./Diagnostics.vue";
const auth = useAuthStore(); const auth = useAuthStore();
@@ -34,7 +33,6 @@ const sections = [
{ id: "pages", label: "Pages", component: ManagePages }, { id: "pages", label: "Pages", component: ManagePages },
{ id: "users", label: "Manage Users", component: ManageUsers }, { id: "users", label: "Manage Users", component: ManageUsers },
{ id: "radio", label: "Manage Radio", component: ManageRadio }, { id: "radio", label: "Manage Radio", component: ManageRadio },
{ id: "diagnostics", label: "Diagnostics", component: Diagnostics },
]; ];
const active = ref("place"); const active = ref("place");
@@ -71,6 +69,16 @@ function handleLogout() {
> >
{{ section.label }} {{ section.label }}
</button> </button>
<!-- Logs and incoming request bodies live in Dozzle, outside the
SPA (nginx serves it at /dozzle/ behind the admin check). -->
<a
class="admin-nav-link no-underline"
href="/dozzle/"
target="_blank"
rel="noopener"
>
Logs ↗
</a>
</nav> </nav>
<section class="admin-panel bdr-2 bg-surface"> <section class="admin-panel bdr-2 bg-surface">
-110
View File
@@ -1,110 +0,0 @@
<script setup>
/**
* Admin panel: tail of the backend log.
*
* GET /api/admin/logs returns JSON read from the filesystem, not GraphQL —
* it is not part of the site's data model.
*
* An admin who remounts the component via tab switches re-triggers
* onMounted, which is the desired "refresh on tab change" behaviour.
*/
import { ref, onMounted, computed } from "vue";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
const lines = ref([]);
const logsError = ref("");
const loadingLogs = ref(false);
async function fetchLogs() {
loadingLogs.value = true;
try {
const res = await api.get("/admin/logs", {
fallback: "Failed to load logs",
});
lines.value = res.lines;
logsError.value = "";
} catch (err) {
logsError.value = err.message;
} finally {
loadingLogs.value = false;
}
}
// 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(fetchLogs);
</script>
<template>
<div class="diagnostics">
<h1>Logs</h1>
<p class="hint">
Tail of the backend log (up to 500 lines): HTTP traffic and application
messages, newest last.
</p>
<div class="log-controls">
<label class="hint toggle">
<input type="checkbox" v-model="trafficOnly" /> visitors only
</label>
<Button :disabled="loadingLogs" @click="fetchLogs">
{{ loadingLogs ? "Loading…" : "Refresh" }}
</Button>
</div>
<p v-if="logsError" class="error">{{ logsError }}</p>
<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>
</template>
<style scoped>
.diagnostics {
display: flex;
flex-direction: column;
gap: 8px;
}
.error {
color: var(--color-error, #b91c1c);
}
.hint {
font-size: 0.85rem;
opacity: 0.75;
}
.log-controls {
display: flex;
justify-content: flex-end;
gap: 12px;
align-items: center;
}
.toggle {
display: flex;
gap: 4px;
align-items: center;
cursor: pointer;
}
.log-output {
max-height: 400px;
overflow-y: auto;
padding: 8px;
background: var(--color-surface-tint, #111);
color: var(--color-primary);
font-size: 0.75rem;
line-height: 1.4;
white-space: pre-wrap;
word-break: break-all;
border: 1px solid var(--color-quaternary);
}
</style>