log_var_set
Sets a specified variable to a given value before writing to the access log.
Description
The log_var_set directive allows you to assign a value to a request variable just prior to writing the access log. This feature is useful when you want to include specific dynamic information in your logs based on conditions existing at the time of request processing. The directive can take two to three arguments: the variable to set, the value to assign, and an optional condition specified with if=condition. The value may reference other request or response variables, allowing you to capture a broad range of HTTP information for logging purposes.
When processed, log_var_set checks the specified condition, if provided. If the condition evaluates to true, the value is assigned to the specified variable. The directive operates at various contexts, including http, server, and location, allowing for flexible scope and the ability to inherit or override configurations as necessary. If multiple log_var_set directives are defined for the same variable at different levels, the directive that is closest within the context hierarchy takes precedence.
This module is considered experimental, and its behavior may change in future releases. Users should thoroughly test their configurations to ensure expected logging behavior is achieved based on how variables are set and how conditions are evaluated during request processing.
Config Example
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$log_field1" "$log_field2"';
access_log /var/log/nginx/access.log;
server {
listen 80;
server_name localhost;
location / {
log_var_set $log_field1 $upstream_http_custom_header1;
log_var_set $log_field2 $upstream_http_custom_header2;
proxy_pass http://example.upstream.com;
}
}
}Not all variable values are available at all stages of request processing; ensure the variable is initialized and set before logging.
Be cautious with the condition syntax; using incorrect conditions can lead to unexpected behavior when logging variables.
If a variable is not set due to a condition, it will not appear in the logs, which can affect log analysis. Make sure to validate conditions thoroughly.