将app level username / userid注入nginx / Apache日志

时间:2011-07-25 19:06:34

标签: django apache logging nginx

有没有办法将应用程序级用户名或id(在本例中为django用户名或id)注入Apache或ngnix日志?请注意,我不是在询问HTTP身份验证用户名。

3 个答案:

答案 0 :(得分:14)

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

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配置中使用%{X-Remote-User-Name}o and %{X-Remote-User-Id}o(或类似于nginx),并将信息直接输入到您的日志中。

答案 1 :(得分:2)

我们这样做,只是告诉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然后使用自定义日志捕获它来做类似的事情。

答案 2 :(得分:0)

如果您有用户名的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地址。我的应用服务器是带有Spring安全性的tomcat8。输出是这样的:

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"
相关问题