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.
You can find a comprehensive list of all available variables in the Nginx documentation, but these are some of the most frequently used ones.
Once you've defined your custom log_format, you need to associate it with your access_log directive. In the http block, this applies to all server blocks unless overridden. Within a specific server block, you can define a different format for that server's access logs.
server {
server_name example.com;
access_log /var/log/nginx/example.com.access.log combined;
...
}
server {
server_name api.example.com;
access_log /var/log/nginx/api.example.com.access.log api_format;
log_format api_format '$remote_addr - [$time_local] "$request" $status';
...
}The combined format is a widely used, predefined format in Nginx that includes most of the common variables we discussed. It's a good starting point if you're unsure where to begin.
Experiment with different combinations of variables to create log formats that are most useful for your monitoring and analysis tasks. This might include adding custom headers, request times, or client connection details.
graph TD;
A[Start] --> B{Define log_format};
B --> C[Specify Variables & Strings];
C --> D{Assign format to access_log};
D --> E[Restart Nginx];
E --> F[Analyze Logs];