Web servers and networking · Intermediate · 16 min
Customise Nginx access logs and log requests as JSON
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30.8 (nginx.org repo) · jq from the Ubuntu archive
You will have Nginx writing one JSON object per request, with timings, upstream details and a request ID your app also logs, and you will query that log with jq to find the slowest requests.
On this page
The default Nginx access log is one line of text per request. It is fine for reading by eye, and awkward for anything else: a user agent with a space or a quote in it shifts every field after it, and the line says nothing about how long the request took or which backend answered it. When something is slow at two in the morning, those are the questions you need answered.
In this tutorial you will define a JSON log format, add timing and upstream fields, give every request an ID that your app logs too, leave health checks out of the log, tune the error log, query the result with jq, and turn on buffering for a busy server. You will work with a small demo app on port 9100 behind a new Nginx site on port 8080, so your existing sites are not touched.
JSON logs are what most log shippers and hosted log tools expect, so this format also gets you ready to send logs somewhere central later.
Step 1 · Install jq and start a demo app
Install Nginx from nginx.org first, as in /tutorials/install-nginx-on-ubuntu-26-04.
Install jq, the command-line JSON tool you will query the log with. Python runs the demo app; Ubuntu servers include it, and the command makes sure.
sudo apt-get install -y jq python3
jq --versionCreate a folder for the demo and write the app. It answers ok, waits for ms milliseconds on /slow, and writes its own JSON log line for every request, including the X-Request-ID header Nginx will send it:
mkdir -p ~/log-json-demo
cat > ~/log-json-demo/app.py <<'PY'
import json
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
LOG_PATH = os.path.expanduser("~/log-json-demo/app.log")
log = open(LOG_PATH, "a", buffering=1)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
if url.path == "/slow":
ms = int(parse_qs(url.query).get("ms", ["300"])[0])
time.sleep(ms / 1000)
body = b"ok\n"
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
log.write(json.dumps({
"source": "app",
"path": self.path,
"request_id": self.headers.get("X-Request-ID", ""),
}) + "\n")
def log_message(self, *args):
pass
print("app listening on http://127.0.0.1:9100", flush=True)
ThreadingHTTPServer(("127.0.0.1", 9100), Handler).serve_forever()
PYStart it in a second terminal and leave it running:
python3 ~/log-json-demo/app.pyIt prints app listening on http://127.0.0.1:9100.
Check it worked
Back in the first terminal:
curl -s http://127.0.0.1:9100/
tail -n 1 ~/log-json-demo/app.logYou see ok, then the app's log line with an empty request_id, because nothing has set the header yet.
Step 2 · Define a JSON log format with timings and a request ID
A log_format lives at the http level, and files in /etc/nginx/conf.d/ are included there. The escape=json parameter makes Nginx escape quotes, backslashes and control characters the JSON way, so a strange user agent cannot break the line. Write the format in its own file. Nginx reads conf.d/ in alphabetical order and a format must be defined before any access_log line that names it, so the 00- prefix makes sure this file is read before your site files:
sudo tee /etc/nginx/conf.d/00-log-json.conf > /dev/null <<'CONF'
log_format json_log escape=json
'{'
'"time":"$time_iso8601",'
'"request_id":"$request_id",'
'"remote_addr":"$remote_addr",'
'"method":"$request_method",'
'"uri":"$request_uri",'
'"status":$status,'
'"bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_addr":"$upstream_addr",'
'"upstream_status":"$upstream_status",'
'"upstream_response_time":"$upstream_response_time",'
'"cache_status":"$upstream_cache_status",'
'"referer":"$http_referer",'
'"user_agent":"$http_user_agent"'
'}';
CONFWhat the fields tell you:
request_timeis the whole time Nginx spent on the request, in seconds with millisecond precision, from the first byte read from the client to the last byte sent.upstream_response_timeis the part of that spent waiting on the backend. A bigrequest_timewith a smallupstream_response_timepoints at a slow client or network, not your app. If Nginx tried more than one backend, the value is a comma-separated list, which is why it is a string here.upstream_addrandupstream_statussay which backend answered and what it returned.cache_statusisHIT,MISSand so on when the location usesproxy_cache, and empty otherwise. See/tutorials/cache-upstream-responses-with-nginx-proxy-cache.request_idis 32 random hexadecimal characters that Nginx creates for each request.
status, bytes_sent and request_time are always numbers, so they are written without quotes and jq can sort on them directly. Every other value is quoted, because it can be empty.
Now the site. Its logging lines go in a small file of their own, /etc/nginx/app-demo-logging.conf, so the later steps rewrite only that file. It sits outside conf.d/ on purpose: it holds server-level lines, and conf.d/ is read at the http level.
sudo tee /etc/nginx/app-demo-logging.conf > /dev/null <<'CONF'
access_log /var/log/nginx/app-demo.json.log json_log;
CONF
sudo tee /etc/nginx/conf.d/app-demo.conf > /dev/null <<'CONF'
server {
listen 8080;
server_name _;
include /etc/nginx/app-demo-logging.conf;
location / {
proxy_pass http://127.0.0.1:9100;
proxy_set_header Host $host;
proxy_set_header X-Request-ID $request_id;
add_header X-Request-ID $request_id always;
}
}
CONF
sudo nginx -tThe proxy_set_header line sends the ID to the app, and add_header ... always returns it to the client, even on error responses. When someone reports a failed request, the ID in their browser's network panel leads straight to the matching lines.
An access_log line in a server block replaces the one inherited from nginx.conf, so this site's requests go only to the JSON file, while your other sites keep logging as before.
Apply it:
sudo systemctl reload nginxCheck it worked
Send a request with an awkward user agent, then pretty-print the last log line:
curl -s -A 'Probe "quoted" agent\path' http://127.0.0.1:8080/
sudo tail -n 1 /var/log/nginx/app-demo.json.log | jq .You see ok, then an object with "status": 200, "upstream_addr": "127.0.0.1:9100" and a 32-character request_id. The user_agent shows as Probe \"quoted\" agent\\path: escaped, and jq parsed the line without complaint. With the default text format, that quote would have ended the field early.
Now follow one request through both logs. Read the ID from the response header, then search for it:
rid=$(curl -s -o /dev/null -D - http://127.0.0.1:8080/orders | tr -d '\r' | awk -F': ' 'tolower($1)=="x-request-id"{print $2}')
echo "$rid"
sudo grep -h "$rid" /var/log/nginx/app-demo.json.log ~/log-json-demo/app.logTwo lines print: the Nginx one with "uri":"/orders" and the app one with "source": "app", both carrying the same ID. Make your own app log this header and you can join the two logs on it.
Step 3 · Leave health checks out of the log
A load balancer or uptime monitor that checks /healthz every few seconds can fill most of your log with lines nobody reads. The if= parameter of access_log skips a request when its condition is 0 or empty. A map sets the condition from the path.
Add the map to the format file. A map also lives at the http level, so it belongs in conf.d/:
sudo tee /etc/nginx/conf.d/log-json-skip.conf > /dev/null <<'CONF'
map $uri $log_this_request {
/healthz 0;
default 1;
}
CONF
sudo tee /etc/nginx/app-demo-logging.conf > /dev/null <<'CONF'
access_log /var/log/nginx/app-demo.json.log json_log if=$log_this_request;
CONF
sudo nginx -tsudo systemctl reload nginx$uri is the path without the query string, so /healthz?probe=1 is skipped too. To skip more paths, add a line each; a line starting with ~ takes a regular expression, such as ~^/static/ 0; for static files.
Check it worked
for i in 1 2 3; do curl -s -o /dev/null http://127.0.0.1:8080/healthz; done
curl -s -o /dev/null http://127.0.0.1:8080/home
sudo grep -c '"uri":"/healthz"' /var/log/nginx/app-demo.json.log || true
grep -c '"/healthz"' ~/log-json-demo/app.logThe first count is 0: Nginx served the health checks but did not log them. The second is 3, because the app still received all three. The /home request is in the Nginx log as normal.
Step 4 · Find the slowest requests with jq
Send a few requests that take different lengths of time:
for ms in 50 400 120 900 10; do
curl -s -o /dev/null "http://127.0.0.1:8080/slow?ms=$ms"
doneList the three slowest requests in the log, slowest first:
sudo jq -s -c 'sort_by(.request_time) | reverse | .[:3][] | {request_time, upstream_response_time, uri, request_id}' /var/log/nginx/app-demo.json.log-s reads the whole file into one array so it can be sorted. jq holds that array in memory at several times the file's size, so keep it to files of a few tens of megabytes; for bigger files, filter line by line instead, which needs almost no memory. This prints every request that took longer than a quarter of a second:
sudo jq -c 'select(.request_time > 0.25) | {request_time, uri}' /var/log/nginx/app-demo.json.logAnd this counts responses by status code, a quick first look during an incident:
sudo jq -s -c 'group_by(.status) | map({status: .[0].status, count: length})' /var/log/nginx/app-demo.json.logIf many of your visitors pay for mobile data by the megabyte, bytes_sent is worth a look too: sort on it the same way to find the pages that cost them the most to load.
Check it worked
The first query prints /slow?ms=900 first, with a request_time a little above 0.9, then /slow?ms=400, then /slow?ms=120. The upstream_response_time beside each is almost the same as request_time, so the time went on the app. The second query prints the 900 and 400 ms requests only. The status count shows every request so far as 200.
Step 5 · Give the site its own error log and pick a level
The error log is a different thing from the access log: Nginx writes there when something goes wrong, such as a backend that refuses the connection. Its level sets how much it writes, from most to least: debug, info, notice, warn, error, crit, alert, emerg. Each level includes the ones after it. error is the default; warn adds a few useful warnings without much noise. debug only works with a binary built with --with-debug; the nginx.org packages ship one as nginx-debug, for short troubleshooting sessions only, because it writes a great deal.
Give the demo site its own error log at warn:
sudo tee /etc/nginx/app-demo-logging.conf > /dev/null <<'CONF'
access_log /var/log/nginx/app-demo.json.log json_log if=$log_this_request;
error_log /var/log/nginx/app-demo.error.log warn;
CONF
sudo nginx -tsudo systemctl reload nginxNow stop the app so Nginx has an error to report. Press Ctrl+C in the second terminal.
Check it worked
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/checkout
sudo tail -n 1 /var/log/nginx/app-demo.json.log | jq -c '{status, upstream_status, request_id}'
sudo tail -n 1 /var/log/nginx/app-demo.error.logThe request returns 502. The JSON line shows "status":502 and "upstream_status":"502", and the error log has a line containing something like connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: _, request: "GET /checkout HTTP/1.1", upstream: "http://127.0.0.1:9100/checkout". The error log does not carry the request ID, so match the two by time and URI.
Start the app again in the second terminal:
python3 ~/log-json-demo/app.pyStep 6 · Buffer the access log on a busy site
By default Nginx writes each access log line to disk as the request finishes. On a site handling hundreds of requests a second, that is a lot of small writes. With buffer=, each worker process collects lines in memory and writes them in one go when the buffer fills. flush= sets the longest a line may wait, so a quiet server still writes its lines promptly.
sudo tee /etc/nginx/app-demo-logging.conf > /dev/null <<'CONF'
access_log /var/log/nginx/app-demo.json.log json_log buffer=32k flush=5s if=$log_this_request;
error_log /var/log/nginx/app-demo.error.log warn;
CONF
sudo nginx -tsudo systemctl reload nginxThe trade-off: if Nginx is killed hard, up to five seconds of lines are lost. A normal reload, stop or log reopen writes the buffer out first. Leave buffering off while you are debugging, so lines appear the moment requests finish.
Check it worked
Send a request, look for it straight away, then again after the flush time:
curl -s -o /dev/null http://127.0.0.1:8080/buffer-check
sudo grep -c '"/buffer-check"' /var/log/nginx/app-demo.json.log || true
sleep 6
sudo grep -c '"/buffer-check"' /var/log/nginx/app-demo.json.logThe first count is usually 0, because the line is still in the worker's memory. After six seconds the count is 1.
The nginx.org package's logrotate file rotates every .log file in /var/log/nginx/, so the new files are rotated with the rest:
grep '/var/log/nginx' /etc/logrotate.d/nginxIt prints /var/log/nginx/*.log {. To change how long logs are kept, see /tutorials/manage-log-files-with-logrotate.
When you have finished with the demo, stop the app with Ctrl+C and remove what this tutorial created. Your own sites are not affected:
sudo rm /etc/nginx/conf.d/app-demo.conf /etc/nginx/conf.d/log-json-skip.conf /etc/nginx/app-demo-logging.conf
sudo rm /var/log/nginx/app-demo.json.log /var/log/nginx/app-demo.error.log
rm -r ~/log-json-demo
sudo nginx -t
sudo systemctl reload nginxKeep /etc/nginx/conf.d/00-log-json.conf: to use the format on a real site, add access_log /var/log/nginx/<site>.json.log json_log; to that site's server block, plus the proxy_set_header X-Request-ID $request_id; line in each proxied location.
Next steps
- Use these logs to work back from a symptom in
/tutorials/find-the-cause-of-an-outage-in-server-logs. - Set retention and compression for the new files with
/tutorials/manage-log-files-with-logrotate. - Fill the
cache_statusfield by adding a cache with/tutorials/cache-upstream-responses-with-nginx-proxy-cache. - Spread traffic over several backends, and see
upstream_addrchange, with/tutorials/load-balance-with-nginx-upstream.
Related tutorials
- Write Nginx location blocks that match what you expectYou will build a practice Nginx 1.30 server where every location block labels its responses, predict which block answers each of twelve URLs, check your answers with curl, and fix the alias, regex-order and proxy_pass mistakes that catch most people out.
- Write a server firewall with nftablesYou will write one /etc/nftables.conf with a default-drop input chain, rate-limited SSH, named address sets, counters and logging, and load it over SSH behind a timer that undoes it if you lose your connection.
- Watch a TCP connection open and close with tcpdumpYou will capture a curl request to a local web server with tcpdump on Ubuntu 26.04, read its handshake, data and teardown line by line, see the reset a closed port sends, and save, filter and rotate captures as pcap files.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials