Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting app level username/userid into nginx/Apache log

Is there a way to inject an application level username or id (in this case, the django username or id) into the Apache or ngnix log? Note that I'm not asking about the HTTP auth username.

like image 1000
Parand Avatar asked Jul 25 '11 19:07

Parand


2 Answers

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.

like image 165
Kristian Glass Avatar answered Nov 12 '22 16:11

Kristian Glass


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.

like image 45
Peter Rowell Avatar answered Nov 12 '22 17:11

Peter Rowell