Django 将应用程序级用户名/用户ID注入nginx/Apache日志
是否有方法将应用程序级用户名或id(在本例中为django用户名或id)注入Apache或ngnix日志?请注意,我不是在询问HTTP身份验证用户名。我们这样做,只是告诉Apache存储Django sessionid cookieDjango 将应用程序级用户名/用户ID注入nginx/Apache日志,django,apache,logging,nginx,Django,Apache,Logging,Nginx,是否有方法将应用程序级用户名或id(在本例中为django用户名或id)注入Apache或ngnix日志?请注意,我不是在询问HTTP身份验证用户名。我们这样做,只是告诉Apache存储Django sessionid cookie LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %{sessionid}C" withsession CustomLog logs/example.com-acce
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,然后使用自定义日志来捕获它来执行类似的操作。我目前正在使用一个简短的自定义中间件将此数据添加到响应头中,如下所示:
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
有了这个功能,您就可以在Apache配置中使用(或nginx的类似配置),并将信息直接输入日志。如果您有一个cookie作为用户名,请说“uname”,您可以添加%{uname}C,如下所示:
LogFormat "%{X-Forwarded-For}i %{uname}C %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
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"
这里X-Forwarded-For是用户ip地址。我的应用服务器是带有Spring security的tomcat8。输出如下:
LogFormat "%{X-Forwarded-For}i %{uname}C %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
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"
很好,我不知道日志中的“C”选项,这可能会起作用。谢谢@am70的更新!