Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request.user #120

Open
chymdyugah opened this issue Jan 17, 2021 · 4 comments
Open

Request.user #120

chymdyugah opened this issue Jan 17, 2021 · 4 comments

Comments

@chymdyugah
Copy link

Request headers should include request user and ip address. It helps the aim of logging.

@varicon2020
Copy link

if we get unique request id in logs for
database queries
request GET data / POST body
response data
that would be helpful.

@CarolynWebster
Copy link

The variability of authentication setups would make it tricky to make universal. But here is a system that we use to add additional context to our logs, including user information and ip address.

You can add additional information to the logs using filters:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {"request": {"()": "path.to.filter.LogContextFilter"}},
    "handlers": {
        "console": {
            "class": "logging.StreamHandler", 
            "filters": ["request"]
        },
    },
    "loggers": {
        "django.request": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
    },
}

For the actual LogContextFilter:

import logging
from .request_context import RequestContextMiddleware


class LogContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.
    """

    def filter(self, record):
        record.ip = getattr(RequestContextMiddleware.THREAD, "ip", "local")
        record.uid = getattr(RequestContextMiddleware.THREAD, "uid", "anon")
        return True

The request_context imported file could look something like this:

import threading
from django.utils.deprecation import MiddlewareMixin

class RequestContextMiddleware(MiddlewareMixin):
    THREAD = None

    def process_request(self, request):
        # define a method that can extract the auth token, sso bearer token, or api key and attribute it to the proper user
        request.user = get_user_from_meta(request)
        RequestContextMiddleware.THREAD = threading.local()
        RequestContextMiddleware.THREAD.ip = get_ip(request) or request.get_host()
        RequestContextMiddleware.THREAD.uid = request.user.id if request.user else "anon"

Let us know if something like that works for you.

@iamr0b0tx
Copy link

iamr0b0tx commented Mar 6, 2022

Here is the trick I use

create a CustomLoggingMiddleware

class CustomLoggingMiddleware(LoggingMiddleware):
    def _get_logging_context(self, request, response):
        """
        Returns a map with args and kwargs to provide additional context to calls to logging.log().
        This allows the logging context to be created per process request/response call.
        """
        user = getattr(request, 'user', None)
        user_id = getattr(user, 'id', None)

        return {
            "args": (),
            "kwargs": {
                "extra": {
                    "request": request,
                    "response": response,
                    "tags": {
                        # tag request with user id
                        "user": user_id,
                    }
                }
            },
        }

update settings

MIDDLEWARE = [
    ...,
    'path.to.custom.class.CustomLoggingMiddleware',
    ...,
]

Hope it helps

@chymdyugah
Copy link
Author

I appreciate everyone for the help. Whist i had fixed my need at the time of opening this issue(filters did it), i felt like it would be an improvement on the library.
But like @CarolynWebster had pointed out, variability of user auth setups is a hurdle but ip address, that can be still be achieved, yea?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants