Insert PHP variables into Apache access log

2010-12-02 09:08:00 by Saz

Ever in the need of finding a request of a specific user on your site? As long as authentication is done using basic auth, everything is fine. As soon as the user logged in, Apache writes the username to access.log. But what about, if authentication is done through HTML forms using POST method? No username in the log. Damn it!

Well, you can put the username in the request URL. As long as you don't want to add a bunch of other information like userid, sessionid, ... Instead of logging requests on your own and loosing some capabilities like "How much bytes went through the cable (with or without headers using mod_logio)" or "How long has this request taken until it left Apache?" (sure, you're able to measure the time, PHP was working...), there is a nice solution: apache_note. apache_note is a PHP wrapper function for Apache's table_get and table_set, to pass information between to different apache modules like PHP and Perl in one request. Or logging.

Ok, I got it. How?

In a function which is called on every request (everything else is... hrm... pretty useless) add something like that:

apache_note('sessionid', session_id());

And your LogFormat line in Apache could look like this:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" sessionid: %{sessionid}n" combined

If a request is made and %{sessionid} is not set (like on every static file), than a "-" (dash) will be displayed.

Happy request logging!


Comments

Fork me on GitHub