By default, Nginx logs a wealth of information about incoming requests. However, for more granular analysis, debugging, or security auditing, you'll often want to customize the format of your access logs. This allows you to tailor the logged data to your specific needs, making it easier to extract meaningful insights.
The log_format directive in Nginx is your key to unlocking this customization. You define named formats within the http or server context. These formats then specify the variables and strings that will be written to the access log file.
http {
log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log /var/log/nginx/access.log custom_format;
...
}In the example above, we've defined a format named custom_format. Let's break down some of the common variables you might use:
$remote_addr: The IP address of the client making the request.
$remote_user: The authenticated user if basic authentication is used.
$time_local: The local time of the request in a common log format.
$request: The full request line, e.g., 'GET /index.html HTTP/1.1'.
$status: The HTTP status code returned by Nginx (e.g., 200, 404, 500).
$body_bytes_sent: The size of the response body in bytes.
$http_referer: The URL of the page that referred the client to the current page.
$http_user_agent: The User-Agent string of the client's browser or application.