now | writings | rss | github | twitter | contact

because stuff sold by the gram is always going to be more exciting than stuff sold by the pound

posted to writings on feb 24th, 2007 with tags apache, nerd, and php

apache's default logging includes the username of authenticated clients:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common

but that's only useful if http-based authentication is being used, which isn't too common in a lot of web applications, and so only a dash is logged: - - [01/Feb/2007:00:43:06 -0600] "GET / HTTP/1.1" 200 9471 "-" "Mozilla/5.0 (X11; U; OpenBSD i386; en-US; rv:1.8.1) Gecko/20061103 Firefox/2.0"

for my forum, i wanted to capture the username of logged in users in the log files for debugging and other statistical reasons. since apache doesn't log requests until they are complete, it's possible to tell apache to log something else for a username once it's been determined by the application.

apache's mod_log_config allows the logging of environment variables by using "%{VAR}e" in the format string. since every php page on my site calls a function that authenticates a user's cookies to see if he is logged in, it's just a matter of setting an arbitrary environment variable for apache from that php function:

apache_setenv("MYAPP_USER", $username);

then tell apache to log that variable instead of expanding the usual "%u" parameter with a CustomLog statement:

CustomLog logs/access_log "%h %l \"%{MYAPP_USER}e\" %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""

and now usernames from all of the php pages are logged, defaulting back to the dash when a user is not logged in or the request is for a static file that doesn't run through php: - "jcs" [25/Feb/2007:17:02:53 -0600] "GET / HTTP/1.1" 200 7177 "-" "Mozilla/5.0 (X11; U; OpenBSD i386; en-US; rv:1.8.1) Gecko/20061103 Firefox/2.0" - "-" [25/Feb/2007:17:02:56 -0600] "GET /favicon.ico HTTP/1.1" 200 1150 "-" "Mozilla/5.0 (X11; U; OpenBSD i386; en-US; rv:1.8.1) Gecko/20061103 Firefox/2.0"
Comments? Contact me via Twitter or e-mail.