使用log_format可以包含一系列variables,例如$ http_user_agent:
http://nginx.org/en/docs/http/ngx_http_core_module.html#variables
但是有可能包含一个来自PHP-FPM的variables吗?
例如,我想在access_log包含login用户的ID。
一种可能性是在PHP中设置一个头文件,然后使用$ sent_http_XXX:
log_format inc_info '... [$sent_http_x_user_id] ...'; access_log /var/log/nginx/access.log inc_info; <?php header('X-User-ID: ' . head(USER_ID)); ?>
但是,这是有点不好意思(在向浏览器发送值的时候),如果在PHP中使用register_shutdown_function() (例如,如果要显示数据库处理时间),则不起作用,因为头文件已经发送。
这可以通过以下方式在Apache中完成:
LogFormat "... [%{USER_ID}n] ..." inc_info CustomLog /var/log/httpd/access_log inc_info
与相应的PHP:
if (function_exists('apache_note')) { apache_note('USER_ID', USER_ID); }