【问题标题】:Injecting app level username/userid into nginx/Apache log将应用程序级别的用户名/用户 ID 注入 nginx/Apache 日志
【发布时间】:2011-10-12 20:34:16
【问题描述】:

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

【问题讨论】:

    标签: django apache logging nginx


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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,然后使用自定义日志来捕获它来执行类似的操作。

      【讨论】:

      • 太好了,我不知道日志记录中的“C”选项,这可能会起作用。
      【解决方案3】:

      如果您有用户名的 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"
      

      【讨论】:

        猜你喜欢
        • 2019-10-05
        • 2021-12-28
        • 1970-01-01
        • 2018-07-20
        • 2011-08-19
        • 2016-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多