phpnginxopenrestyaccess-log

php-fpm access log should contain custom variables set from php application


Pre

Current setup is made with apache+mod_php. We are able to put in apache access log userId and sessionId set from the code by using apache_setenv and then in access log we got:

"\"%{USER_ID}e\" \"%{SESSION_ID}e\""

This is necessary for us to be able to debug information easily based on access logs.

Feature

Consider the following setup: php application that runs on php-fpm with nginx as a reverse proxy.

I want to move to move to containerised application that is using php-fpm and nginx. The problem is that I'm not table to log dynamic variables to nginx or php-fpm log using $_ENV. The data exists in the dump of $_SERVER but then is not accessible neither from php-fpm or nginx-acces log.

Question

  1. If Im able to set fastcgi_param in nginx from env variable that comes from application case is closed. Using lua in nginx with os.getenvvariable should do the trick?
  2. In php-fpm access log format %{userId}e and %{sessionId}e despite the fact that they exist in var_dump($_SERVER). If I pass from nginx fastcgi_param with static value I can access such environment variable in php-fpm.

Is there any other options to make this go or LUA in nginx is the only option. Currently I'm about to try out.


Solution

  • My solution ended using custom http headers:

    header("UserId: 1");
    header("SessionId: session_id");
    

    and then in nginx access log

    log_format main "$upstream_http_userid $upstream_http_sessionid";
    

    in case of apache access log

    LogFormat "%h %l %u %t \"%r\" %>s %O %{UserId}o %{SessionId}o"