How to get username in django_requestlogging

Hello Everyone,

I am using ‘django_requestlogging’ for the log file and I have followed https://pypi.org/project/django-requestlogging/ this link and configured it as per the steps given.

I am not getting the username in the log file instead of that I am getting “-”.

Please find the code details.

step1.Installed application
INSTALLED_APPS = [
-------
------
'django_requestlogging',
]

step2:
Created Middleware
from django.utils.deprecation import MiddlewareMixin
from django_requestlogging.middleware import LogSetupMiddleware as Original

class LogSetupMiddleware(MiddlewareMixin, Original):
    pass

step3:
used in settings.py
MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
‘user_visit.middleware.UserVisitMiddleware’,
# ‘django_requestlogging.middleware.LogSetupMiddleware’,
‘apple.middleware1.LogSetupMiddleware’
]

step4:
Configuration

    LOGGING = {
        'version': 1,
        # Version of logging
        'disable_existing_loggers': False,
        'filters': {
            # Add an unbound RequestFilter.
            'request': {
                '()': 'django_requestlogging.logging_filters.RequestFilter',
            },
        },
        'formatters': {
            'request_format': {
                             'format': '[%(asctime)s] - %(levelname)5s -:%(message)3s -" %(username)5s'
      
                             },
                    'simple': {
                               'format': '[%(asctime)s] - %(levelname)5s -:%(message)3s -" %(username)5s'
                              },
                     },
        'handlers': {
            'console': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'filters': ['request'],
                'formatter': 'request_format',
            },

            'file': {
                'level': 'INFO',
                'class': 'logging.FileHandler',
                'filename': 'icici.log',
                'formatter': 'request_format',
            },
        },
        'loggers': {
           'django': {
                # Add your handlers that have the unbound request filter
                'handlers': ['console','file'],
                'level': 'DEBUG',
                'propagate': True,
                # Optionally, add the unbound request filter to your
                # application.
                'filters': ['request'],
            },
        },
    }

In the O/p Log file, I am getting.

[2021-01-01 21:53:39,243] - INFO -:"GET /genesysall/ HTTP/1.1" 200 82259 -" -
Any help or hint on this how to get the username.

Hi,

it looks like you are using the wrong formatter. try to position the username in the request_format formatter, and take this format from the handler. In your handlers you only take the simple formatter and the request_format formatter is never used.

Hi @AlvesInfo,
Thanks for your help I have made changes in my code but with no luck still I am not getting the login username. I am getting the below output.
[2021-01-03 11:47:16,569] - INFO -:"GET /ctsall/ HTTP/1.1" 200 72181 -" -
An alternative of this I thought to use below the line in my views but it is not showing in the log file.
logger.info(‘CTDashboard Page is opened!’,request.user.username)

Hi,
have you add django_requestlogging to settings.INSTALLED_APPS, and add django_requestlogging.middleware.LogSetupMiddleware to settings.MIDDLEWARE_CLASSES?

were you logged in?
if you not logued, no have username in request

Hi @AlvesInfo,

If I follow the document (a step you suggested ).
Install the package, add django_requestlogging to settings.INSTALLED_APPS, =>Yes

add django_requestlogging.middleware.LogSetupMiddleware to settings.MIDDLEWARE_CLASSES, =>for this I have manually created LogSetupMiddleware however if I am defining it directly inside MIDDLEWARE as shown below I am getting

|Exception Type:|TypeError|
| — | — |
|Exception Value:|‘LogSetupMiddleware’ object is not callable

MIDDLEWARE = [
                     -----------
    'django_requestlogging.middleware.LogSetupMiddleware'

   ]

were you logged in?
-Yes I am checking it after the user login.

Hi,
If we do not put pass in the middleware class, but just a comment, there is no longer the error, but it still does not log.
this module is very old (2011) and it seems that the middleware no longer works with recent versions of django.
you should try, the first answer from stackoverflow:

I think it will work after.
good luck
Paulo

1 Like
LOGGING = {
    'version': 1,
    # Version of logging
    'disable_existing_loggers': False,

    ###########Filter#####################
    # 'filters': {
    #     # Add an unbound RequestFilter.
    #     'request': {
    #         '()': 'django_requestlogging.logging_filters.RequestFilter',
    #     },
    # },

    #########formatter#########################
        'formatters': {
          'verbose': {
                      'format': '%(levelname)s - %(asctime)s-- %(module)s - %(process)d - %(thread)d - %(message)s'
},
        'simple': {
            'format': '[%(asctime)s] - %(levelname)5s : %(message)s %(user)s'
        },
         
    },
#########################Handlers ##################################
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': 'tik.log',
            'formatter': 'simple'
        },

        'console': {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
        },
    },
################################ Loggers ##############################(A single Logger can have multiple handler )

    'loggers': {
        'django': {
            'handlers': ['file','console'],
            'level': 'DEBUG',
            'propagate': True,
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
    },
}

Hi @AlvesInfo,
Where do I need to add logging.Filter and how to use it in logger configuration.
https://stackoverflow.com/a/10294761/12487254 and code is

    class RequestUserFilter(logging.Filter):
        def filter(self, record):
            record.user = record.request.user
            return True
    ```