TExcelTAD

Access Log Formats

The proxy's access log is the single best record of what your users experienced: every request, its status, how long it took, which backend answered and why a request failed. The default formats are made for humans reading one line at a time; in production you want structured logs (JSON) with timing and upstream fields, shipped to a log system such as Loki or Elasticsearch (Observability). This lesson configures that in all four servers and reads the results with jq.

Nginx: a JSON format with upstream timing

nginx
log_format json_combined escape=json '{'
  '"time":"$time_iso8601","request_id":"$request_id",'
  '"remote_addr":"$remote_addr","method":"$request_method","uri":"$request_uri",'
  '"status":$status,"bytes":$body_bytes_sent,'
  '"request_time":$request_time,'
  '"upstream":"$upstream_addr","upstream_status":"$upstream_status",'
  '"upstream_connect_time":"$upstream_connect_time","upstream_response_time":"$upstream_response_time",'
  '"cache":"$upstream_cache_status","user_agent":"$http_user_agent"}';
access_log /var/log/nginx/access.json json_combined buffer=64k flush=5s;
Variable Meaning
$request_time seconds from the first byte read from the client to the last byte sent (includes slow clients)
$upstream_response_time time the backend took; several values (0.002, 1.001) when Nginx retried on another server
$upstream_connect_time TCP (+TLS) connect time to the backend: high values mean an overloaded backend or network
$upstream_addr / $upstream_status which backend(s) answered, and with what; also comma-separated after retries
$request_id a random 32-hex id per request (since 1.11.0); send it to the app with proxy_set_header X-Request-ID $request_id; to correlate logs

escape=json (since 1.11.8) makes Nginx escape quotes and control characters properly. The upstream variables are strings (they can be - or lists), so quote them; $status and $request_time are always numbers.

bash · try it yourself
cat > app.py <<'EOF'
import sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/slow": time.sleep(0.3)
        self.send_response(500 if sys.argv[2] == "bad" else 200); self.end_headers(); self.wfile.write(b"ok\n")
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 bad & python3 app.py 9002 good &
for p in 9001 9002; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  log_format json_combined escape=json '{'
    '"request_id":"$request_id","method":"$request_method","uri":"$request_uri","status":$status,'
    '"request_time":$request_time,"upstream":"$upstream_addr","upstream_status":"$upstream_status",'
    '"upstream_response_time":"$upstream_response_time","user_agent":"$http_user_agent"}';
  access_log access.json json_combined;
  upstream app { server 127.0.0.1:9001 max_fails=0; server 127.0.0.1:9002 max_fails=0; }
  server {
    listen 127.0.0.1:8080;
    location / {
      proxy_pass http://app;
      proxy_next_upstream error timeout http_500;
      proxy_set_header X-Request-ID $request_id;
    }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
curl -s -o /dev/null 127.0.0.1:8080/fast
curl -s -o /dev/null 127.0.0.1:8080/slow
curl -s -o /dev/null -A 'evil "quoted" agent' 127.0.0.1:8080/x
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; sleep 0.3
jq -c '{uri, status, upstream, upstream_status, user_agent}' access.json
echo "--- every line is valid JSON: $(jq -s length access.json) records"
echo "--- request ids are 32 hex chars: $(jq -r .request_id access.json | grep -cE '^[0-9a-f]{32}
  

)"
echo "--- slow requests (> 0.25 s): $(jq -r 'select(.request_time > 0.25) | .uri' access.json)"
kill %1 %2
{"uri":"/fast","status":200,"upstream":"127.0.0.1:9001, 127.0.0.1:9002","upstream_status":"500, 200","user_agent":"curl/8.5.0"}
{"uri":"/slow","status":200,"upstream":"127.0.0.1:9002","upstream_status":"200","user_agent":"curl/8.5.0"}
{"uri":"/x","status":200,"upstream":"127.0.0.1:9001, 127.0.0.1:9002","upstream_status":"500, 200","user_agent":"evil \"quoted\" agent"}
--- every line is valid JSON: 3 records
--- request ids are 32 hex chars: 3
--- slow requests (> 0.25 s): /slow

Round-robin sent two of the three requests to the broken backend first; each got a 500 and was retried on the good one: upstream and upstream_status list both attempts, while the client only saw the final 200. Without those fields, this failing backend would be invisible in the logs. The user agent with quotes stayed valid JSON thanks to escape=json.

Useful extras: access_log … if=$loggable; with a map $status $loggable { ~^[23] 0; default 1; } logs only errors on a busy site; access_log off; for health-check locations; buffer= and flush= reduce disk writes.

HAProxy: httplog and its timers

HAProxy logs through syslog (or to stdout in containers). option httplog gives a dense line with timers and a termination state that explain almost any failure:

bash · try it yourself
cat > app.py <<'EOF'
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/slow": time.sleep(3)
        self.send_response(200); self.end_headers(); self.wfile.write(b"ok\n")
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
cat > haproxy.cfg <<'EOF'
global
  log stdout format raw local0
defaults
  mode http
  log global
  option httplog
  timeout connect 1s
  timeout client 10s
  timeout server 1s
frontend fe
  bind 127.0.0.1:8080
  use_backend be_dead if { path_beg /dead }
  default_backend be_app
backend be_app
  server app1 127.0.0.1:9000
backend be_dead
  retries 0
  server dead 127.0.0.1:9999               # nothing listens here
EOF
haproxy -f haproxy.cfg > haproxy.log 2>&1 &                # foreground, logs on stdout
for i in $(seq 50); do curl -s 127.0.0.1:8080/ > /dev/null && break; sleep 0.1; done
curl -s -o /dev/null 127.0.0.1:8080/ok         # normal
curl -s -o /dev/null 127.0.0.1:8080/dead       # connection refused
curl -s -o /dev/null 127.0.0.1:8080/slow       # slower than "timeout server"
kill %2; sleep 0.3
tail -1 haproxy.log | sed -E 's/^127.0.0.1:[0-9]+ \[[^]]*\]/127.0.0.1:<port> [<date>]/; s#( -?[0-9]+/-?[0-9]+/-?[0-9]+/-?[0-9]+/)[0-9]+ #\1<Ta> #'
echo "--- the fields that matter (server, Tc, Tr, status, termination state, path):"
tail -3 haproxy.log | sed -E 's/^.*\] //' | awk '{split($3, t, "/"); printf "%-14s Tc=%-3s Tr=%-3s %s %s %s\n", $2, t[3], t[4], $4, $8, $12}'
kill %1
127.0.0.1:<port> [<date>] fe be_app/app1 0/0/0/-1/<Ta> 504 198 - - sH-- 1/1/0/0/0 0/0 "GET /slow HTTP/1.1"
--- the fields that matter (server, Tc, Tr, status, termination state, path):
be_app/app1    Tc=0   Tr=0   200 ---- /ok
be_dead/dead   Tc=-1  Tr=-1  503 SC-- /dead
be_app/app1    Tc=0   Tr=-1  504 sH-- /slow

A full line reads: client address and port, date, frontend, backend/server, the five timers TR/Tw/Tc/Tr/Ta in milliseconds, status, bytes, two cookie fields, the four-character termination state, connection counts, queue positions and the request line. (The session replaces the port, date and total time, which change on every run.) The second part picks out the fields that explain the three outcomes:

Timer Meaning A high or -1 value means
TR time to receive the full request from the client slow client / big upload
Tw time waiting in queues servers at maxconn
Tc time to connect to the server -1: connection failed
Tr server response time (headers) -1: no response (timeout or error)
Ta total time active

The first character of the termination state says who ended the session (C client, S server, s server-side timeout, c client-side timeout, P proxy, - normal end) and the second when (R request, C connect, H headers, D data). So SC is "the server refused the connection", sH is "server timeout while waiting for headers": two different incidents that both look like "504/503" from the outside. option log-health-checks, log-format (a fully custom format, including JSON) and option dontlognull round out the logging options.

Caddy and Traefik: JSON by default

text
# Caddyfile
shop.example {
	log {
		output file /var/log/caddy/access.json {
			roll_size 100MiB
			roll_keep 10
		}
		format json
	}
	reverse_proxy 127.0.0.1:9000
}
yaml
# traefik.yml (static configuration)
accessLog:
  filePath: /var/log/traefik/access.json
  format: json
  bufferingSize: 100
  filters:
    statusCodes: ["400-599"]          # only errors
    minDuration: 500ms                # or slow requests
  fields:
    headers:
      defaultMode: drop               # don't log headers (they can contain tokens)
      names:
        User-Agent: keep

Caddy's access log entries hold the request (with headers), status, duration and size; Traefik's hold RequestPath, DownstreamStatus, OriginStatus, Duration (nanoseconds) and the router and service names (RouterName, ServiceName), which makes per-route dashboards easy. Both redact sensitive headers poorly unless told: never log Authorization or Cookie headers, and treat query strings as sensitive too (tokens end up in them).

Test yourself

An Nginx log line shows upstream_status: "500, 200". What happened?

  1. Two clients made requests
  2. The first backend answered 500 and Nginx retried the request on a second backend, which answered 200
  3. The response was cached
  4. The log is broken

HAProxy logs a request with termination state sH. What does it mean?

  1. The client closed the connection
  2. A server-side timeout expired while waiting for the response headers
  3. The server refused the connection
  4. Normal completion

Why add escape=json to an Nginx JSON log_format?

  1. Compression
  2. So that quotes and control characters in values (user agents, URIs) are escaped and every line stays valid JSON
  3. It's required for $request_id
  4. Speed