Skip to content

Nginx logs — access format, error levels, and logrotate that does not lose lines

How to define an access log format Nginx can emit (including JSON), tune error_log levels, and configure logrotate so reload during rotation does not lose log lines.

The default Nginx combined log format is a string optimised for human eyes and grep. The modern setup is JSON access logs, an explicit error_log level per site, and a logrotate config that signals Nginx properly so a rotated file is not still being written into. None of this is hard; all of it is wrong by default on a fresh install in subtle ways that show up six months later when you try to parse logs at scale.

How to verify

See the current state of logging:

sudo nginx -T | grep -E 'access_log|error_log|log_format'
ls -la /var/log/nginx/
sudo head -3 /var/log/nginx/access.log
cat /etc/logrotate.d/nginx
sudo logrotate -d /etc/logrotate.d/nginx 2>&1 | head

logrotate -d runs in debug mode — shows what would be done without doing it.

What’s happening

access_log and error_log are the two log directives. Access logs record requests; error logs record errors and (depending on level) operational notices. The log_format directive lets you define a custom shape; you reference it from access_log.

Logrotate runs daily from a systemd timer (or cron). The default /etc/logrotate.d/nginx does copytruncate or postrotate + a signal — different distributions ship different defaults. The trap: if logrotate moves access.log to access.log.1 without telling Nginx, Nginx is still writing into the (now moved) file descriptor and the “rotated” file keeps growing while the new one stays empty. The fix is sending Nginx a USR1 signal in a postrotate hook — Nginx reopens its log files cleanly.

JSON formats matter because grep-style logs are unparseable past a million lines a day. Shipping structured logs to Loki, Elasticsearch, or CloudWatch needs JSON in, not Apache combined.

The procedure

  1. Define a JSON access log format in nginx.conf under http {}:
    log_format json_combined escape=json '{'
        '"ts":"$time_iso8601",'
        '"client":"$remote_addr",'
        '"method":"$request_method",'
        '"path":"$request_uri",'
        '"status":$status,'
        '"bytes":$body_bytes_sent,'
        '"referer":"$http_referer",'
        '"ua":"$http_user_agent",'
        '"xff":"$http_x_forwarded_for",'
        '"req_time":$request_time,'
        '"ups_addr":"$upstream_addr",'
        '"ups_status":"$upstream_status",'
        '"ups_time":"$upstream_response_time",'
        '"cache":"$upstream_cache_status"'
        '}';
    
    access_log /var/log/nginx/access.log json_combined;
    error_log  /var/log/nginx/error.log  warn;
    escape=json (Nginx 1.11.8+) is essential — it escapes embedded quotes correctly.
  2. Per-site overrides. Set the access_log on each server block so each site has its own file:
    server {
        server_name example.com;
        access_log /var/log/nginx/example.com.access.log json_combined;
        error_log  /var/log/nginx/example.com.error.log  warn;
        # ...
    }
  3. Decide the error_log level. The options are debug, info, notice, warn, error, crit, alert, emerg. Production lives at warn or error. info includes every request — only useful for one-off troubleshooting. debug requires Nginx compiled with --with-debug.
  4. Logrotate config (/etc/logrotate.d/nginx):
    /var/log/nginx/*.log {
        daily
        missingok
        rotate 14
        compress
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        postrotate
            if [ -f /run/nginx.pid ]; then
                kill -USR1 $(cat /run/nginx.pid)
            fi
        endscript
    }
    delaycompress compresses on the next rotation, not the immediate one, so the most recent rotated file is still readable as plain text. sharedscripts runs postrotate once for all matching files. The USR1 signal tells Nginx to close and reopen all log files.
  5. Test the rotation logic without waiting a day:
    sudo logrotate -f /etc/logrotate.d/nginx
    ls -la /var/log/nginx/
    sudo journalctl -u nginx -n 10
  6. If shipping logs externally (Loki, Promtail, Vector, fluent-bit), point the agent at the JSON files. The structured fields land as labels automatically.
  7. Decide on retention. rotate 14 keeps two weeks; for compliance keep longer, but ship to centralised storage so local disks do not balloon.

Common pitfalls

  • copytruncate instead of postrotate USR1 — works but loses log lines written between the copy and the truncate. Avoid.
  • Compressing the active log. With delaycompress the freshest rotated file is uncompressed; without it, tail -f /var/log/nginx/access.log.1.gz is a non-starter.
  • Logging $request_body — the body can be megabytes and is not safe with secrets. Log only the URI + status + size unless you have a specific reason.
  • Forgetting per-site log files. One big shared access.log is fine until you need to know which site got DDoS’d at 03:00.
  • Disk fill from error_log info left on after troubleshooting. Set a calendar reminder to reset to warn, or template the value and never edit by hand.

In the engagements we run, log format is set once by the Ansible role that owns Nginx config, and rotation lives in the OS image — drift between hosts is not allowed. The structured JSON ships into the central log pipeline, and dashboards in managed operations read from there rather than ssh’ing into individual boxes.