将应用程序级用户名/用户标识注入到nginx / Apache日志中

有没有办法将应用程序级别的用户名或ID(在本例中是django用户名或ID)注入到Apache或ngnix日志中? 请注意,我不是在询问HTTPauthentication用户名。

我们这样做,只有我们告诉Apache来存储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 

将sessionid映射到用户是一个两步的过程,但实现起来很简单。 你可以通过设置一个具有显式ID的cookie来做类似的事情,然后使用自定义日志来捕获它。

我目前正在使用一个简短的自定义中间件来将这些数据添加到响应头中,如下所示:

 class RemoteUserMiddleware(object): 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 

有了这个,你可以在你的Apache配置文件(或类似的nginx)中使用%{X-Remote-User-Name}o%{X-Remote-User-Id}o

如果你有一个用户名的cookie,说“uname”,你可以添加%{uname} C,如下所示:

 LogFormat "%{X-Forwarded-For}i %{uname}C %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined 

这里的X-Forwarded-For是用户的IP地址。 我的应用程序服务器是Tomcat8的Spring安全。 输出是这样的:

 24.xx.xx.xxx user.name - - [09/Sep/2016:19:33:21 -0400] "GET /xxxx HTTP/1.1" 304 - "https://xxx/xxx" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"