Master Nginx Access & Error Logs: Config, Custom Formats, Auto Rotation
This guide explains how Nginx’s access_log and error_log work, details the log_format directive for customizing access logs, shows how to configure log paths, formats, buffering, compression, and conditional logging, and provides a Bash script with a cron job to automatically rotate daily log files.
Nginx logs are essential for statistics and troubleshooting. There are two main logs: access_log (records client requests) and error_log (records errors).
Access logs capture client IP, user‑agent, referer, request time, URL, status code, and other variables. The log_format directive defines the layout of each line.
log_format main '$server_name $remote_addr - $remote_user [$time_local] "$request" '
'$status $uptream_status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$ssl_protocol $ssl_cipher $upstream_addr $request_time $upstream_response_time';Common variables include $server_name, $remote_addr, $remote_user, $time_local, $request, $status, $uptream_status, $body_bytes_sent, $http_referer, $http_user_agent, $http_x_forwarded_for, $ssl_protocol, $ssl_cipher, $upstream_addr, $request_time, and $upstream_response_time. The log_format must be placed inside the http block.
The access_log directive specifies the file path, format, buffer size, gzip compression, flush interval, and optional condition.
# Set access log
access_log /var/logs/nginx-access.log;
access_log logs/access.log main;
access_log /var/logs/nginx-access.log buffer=32k gzip flush=1m;
# Disable logging
access_log off;The error_log directive defines the file path and log level (debug, info, notice, warn, error, crit). The default level is error.
error_log logs/error.log info;
# Disable error logging (writes to /dev/null)
error_log /dev/null;Log rotation can be automated with a Bash script that copies the current logs to a dated file and truncates the original files, then scheduled via cron to run daily at midnight.
#!/bin/bash
LOGS_PATH=/usr/local/nginx/logs
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)
cp ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${YESTERDAY}.log && > ${LOGS_PATH}/access.log
cp ${LOGS_PATH}/error.log ${LOGS_PATH}/error_${YESTERDAY}.log && > ${LOGS_PATH}/error.logCron entry:
0 0 * * * /usr/local/nginx/logs/NginxLogRotate.shSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
