0

Im thinking on how to retrieve Django user data on the user authetication class and pass it to Nginx session variables, then on the nginx logging settings use that data to create a Nginx access log entry that contains the Django user that create such a request.

I have found these ideas:

  1. Get current request by Django's or Python threading https://gist.github.com/vparitskiy/71bb97b4fd2c3fbd6d6db81546622346 https://nedbatchelder.com/blog/201008/global_django_requests.html

  2. Set a session variable: How can I set and get session variable in django?

  3. And then log the cookie variable via a Nginx configuration like: https://serverfault.com/questions/223584/how-to-add-recently-set-cookies-to-nginxs-access-log https://serverfault.com/questions/872375/what-is-the-difference-between-http-cookie-and-cookie-name-in-nginx

Any better idea?. I'm reinventing the wheel?

Franco Milanese
  • 402
  • 3
  • 7

2 Answers2

2

Finally I have done this. Place a middleware en Django that insert in the cookies the logging data that I want nginx to log.

Then I used the $upstream_cookies_NAME to rescue the COOKIES['NAME'] if any.

Franco Milanese
  • 402
  • 3
  • 7
0

have you read django's documentation on logging?

I haven't worked with nginx, yet, but with apache djangos default logger also outputs to the apache log, meaning that you can do this:

from logging import getLogger
logger = getLogger('django')

def my_view(request):
    logger.info(f'my view: {request.user}') 

which will output the user to the server log.

SMoenig
  • 486
  • 3
  • 11
  • Yes, I have know about python logging module. But the issue with this approach is that every endpoint (or view) on Django has to have a logging method execution in order to cause a log to nginx log file. Also this logging log probably will have a different structure as the ones of nginx, causing another "normalization" issue. Instead I'm thinking something like if Nginx response knows the django user id then, logs it. Just like with the forwarded IPs and proxies. – Franco Milanese Mar 18 '21 at 03:58