Giter Site home page Giter Site logo

Request.user about django-request-logging HOT 4 OPEN

rhumbix avatar rhumbix commented on June 30, 2024
Request.user

from django-request-logging.

Comments (4)

iamr0b0tx avatar iamr0b0tx commented on June 30, 2024 1

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

from django-request-logging.

varicon2020 avatar varicon2020 commented on June 30, 2024

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

from django-request-logging.

CarolynWebster avatar CarolynWebster commented on June 30, 2024

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.

from django-request-logging.

chymdyugah avatar chymdyugah commented on June 30, 2024

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?

from django-request-logging.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.