Injecting app level username/userid into nginx/Apache log

I'm currently using a short custom middleware to add this data to response headers, as below:

from django.utils.deprecation import MiddlewareMixin
class RemoteUserMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if request.user.is_authenticated:
            response['X-Remote-User-Name'] = request.user.username
            response['X-Remote-User-Id'] = request.user.id
        return response

With this in place, you can just use %{X-Remote-User-Name}o and %{X-Remote-User-Id}o in your Apache config (or similar for nginx) and get the information straight into your logs.


We do something like this, only we tell Apache to store the the Django sessionid cookie.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %{sessionid}C" withsession
CustomLog logs/example.com-access_log withsession

It's sort of a two-step process to map the sessionid to the user, but it's easy to implement. You could do something similar by setting a cookie with the explicit ID in it and then using the custom log to capture it.