Configuring Client Request Logging in Nginx

Nginx provides a robust mechanism for tracking incoming client interactions through its access logging feature. Every HTTP or stream transaction is captured, enabling administrators to monitor traffic patterns, debug routing issues, and analyze usage metrics. The core directive responsible for this functionality is access_log.

Directive Overview and Context

The access_log directive can be applied across multiple configuration contexts, including http, server, location, if blocks, and limit_except. In the stream context, logging is disabled by default and must be explicitly enabled.

access_log off;

Parameter Breakdown

The directive follows a flexible syntax that allows fine-tuning of how, where, and when log entries are written. Multiple log definitions can coexist within the same configuration block.

  • Destination Path: Specifies the target file location or a syslog server endpoint. If omitted, Nginx defaults to writing to a local file.
  • Log Format: References a named template defined via the log_format directive. This determines which variables and structures are recorded for each request.
  • Memory Buffer: Controls the size of the in-memory staging area before data is flushed to persistent storage. The standard allocation is 64 kilobytes. Increasing this value can reduce disk I/O overhead during high-traffic periods.
  • Flush Interval: Defines a time threshold. Evenif the buffer isn't full, entries older than this duration are automatically written to the disk.
  • Compression: Enables on-the-fly gzip compression for log files. Levels range from 1 (fastest) to 9 (highest compression). Higher levels consume more CPU resources.
  • Conditional Logging: Allows selective recording based on request metadata. Logging only occurs when the evaluated expression returns a non-empty or non-zero value.

Configuration Examples

Below are practical implementations demonstrating various parameter combinations.

Basic File Output with Custom Template

access_log /var/log/nginx/traffic.log json_combined;

Compressed Logs with Buffer Tuning

access_log /data/archive/requests.log.gz standard gzip=4 buffer=256k flush=15m;

Conditional Logging Based on Response Status

To reduce noise, you might only want to log requests that result in server errors or specific redirect codes. This can be achieved by mapping a variable and applying it as a condition.

map $status $record_entry {
    ~^[23]    0;
    default   1;
}

access_log /var/log/nginx/server_errors.log trace_format if=$record_entry;

In this setup, the map directive evaluates the HTTP response code. Successful (2xx) and redirection (3xx) responses are excluded, while client (4xx) and server (5xx) errors trigger the logging mechanism.

Tags: nginx access-log log-configuration web-server server-management

Posted on Fri, 24 Jul 2026 16:56:15 +0000 by joeami