vishalanandl177 / DRF-API-Logger

An API Logger for your Django Rest Framework project.
https://github.com/vishalanandl177/DRF-API-Logger
Apache License 2.0
308 stars 56 forks source link

Follow README but log nothing #68

Closed dyhe83 closed 1 year ago

dyhe83 commented 2 years ago

Hi,

I follow README to add app, middleware and some settings in settings.py.

The admin panel have new page: http://localhost/admin/drf_api_logger/apilogsmodel/

But no log show up.

I called API work as expect.

method = GET
url = http://localhost:3000/

response = Hello!!

Django log

Performing system checks...

Watching for file changes with StatReloader
System check identified no issues (0 silenced).
October 16, 2022 - 11:49:57
Django version 3.2.16, using settings 'DrfLogTest.settings'
Starting development server at http://0.0.0.0:3000/
Quit the server with CTRL-BREAK.
[16/Oct/2022 11:50:09] "GET /admin/drf_api_logger/apilogsmodel/ HTTP/1.1" 200 8690
[16/Oct/2022 11:50:09] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
[16/Oct/2022 11:50:13] "GET / HTTP/1.1" 200 140
[16/Oct/2022 11:50:14] "GET / HTTP/1.1" 200 140
[16/Oct/2022 11:50:15] "GET / HTTP/1.1" 200 140
[16/Oct/2022 11:50:15] "GET / HTTP/1.1" 200 140
[16/Oct/2022 11:50:15] "GET / HTTP/1.1" 200 140
[16/Oct/2022 11:50:15] "GET / HTTP/1.1" 200 140
[16/Oct/2022 11:50:15] "GET / HTTP/1.1" 200 140

I also copy the signal example code and it doesn't print anything either.

Is there anything I forget to setup??

Run pip freeze

asgiref==3.5.2
beautifulsoup4==4.11.1
bleach==5.0.1
bs4==0.0.1
certifi==2022.9.24
charset-normalizer==2.1.1
Django==4.1.2
django-tables2==2.4.1
djangorestframework==3.14.0
drf-api-logger==1.1.11
idna==3.4
keyboard==0.13.5
psycopg2==2.9.4
python-vlc==3.0.16120
pytz==2022.4
requests==2.28.1
six==1.16.0
soupsieve==2.3.2.post1
sqlparse==0.4.3
typing-extensions==4.4.0
urllib3==1.26.12
webencodings==0.5.1

settings.py as follow.

"""
Django settings for DrfLogTest project.

Generated by 'django-admin startproject' using Django 3.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from config import database_config

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$t=lyl(()ytv0%vx9^^o_-zivv%upc&&n0o#l4%g#=o!u07!m0'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django_tables2',

    'rest_framework',
    'crawler',

    'drf_api_logger',
]

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',

    'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware',
]

ROOT_URLCONF = 'DrfLogTest.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DrfLogTest.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
        # 'ENGINE': 'django.db.backends.postgresql_psycopg2',
        # 'NAME': database_config.name,
        # 'USER': database_config.user,
        # 'PASSWORD': database_config.password,
        # 'HOST': database_config.host,
        # 'PORT': database_config.port,
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

SITE_ID = 1

# drf logger
DRF_API_LOGGER_DATABASE = True
DRF_API_LOGGER_SIGNAL = True
DRF_API_LOGGER_METHODS = ['GET', 'POST', 'DELETE', 'PUT']
DRF_API_LOGGER_STATUS_CODES = ['200', '400', '404', '500']
DRF_LOGGER_QUEUE_MAX_SIZE = 1
DRF_LOGGER_INTERVAL = 1
kfsz commented 1 year ago

I think the issue here may be with DRF_API_LOGGER_STATUS_CODES setting.

Although readme suggests that it should be a list of strings, these strings are later being compared to DRF's status codes, which are numeric (https://www.django-rest-framework.org/api-guide/responses/#status_code) so none of them will match.

https://github.com/vishalanandl177/DRF-API-Logger/blob/b805a28d4f5a298de4d01718eb6bfbef76b114e2/drf_api_logger/middleware/api_logger_middleware.py#L90-L92

Changing the setting to DRF_API_LOGGER_STATUS_CODES = [200, 400, 404, 500] has fixed the problem for me.

(I was also surprised that requests made using DRF's Browsable API weren't being logged - but that was on me, as only requests with "application/json" content-type response are.)

vishalanandl177 commented 1 year ago

It will log only 'ContentType application/json' in Django Rest Framework. It will log only if the request and response both are json.

vishalanandl177 commented 1 year ago

Closing due to inactivity.

dyhe83 commented 1 year ago

It will log only 'ContentType application/json' in Django Rest Framework. It will log only if the request and response both are json.

Got it, thanks!

lawebb-CDL commented 1 year ago

I think the issue here may be with DRF_API_LOGGER_STATUS_CODES setting.

Although readme suggests that it should be a list of strings, these strings are later being compared to DRF's status codes, which are numeric (https://www.django-rest-framework.org/api-guide/responses/#status_code) so none of them will match.

https://github.com/vishalanandl177/DRF-API-Logger/blob/b805a28d4f5a298de4d01718eb6bfbef76b114e2/drf_api_logger/middleware/api_logger_middleware.py#L90-L92

Changing the setting to DRF_API_LOGGER_STATUS_CODES = [200, 400, 404, 500] has fixed the problem for me.

(I was also surprised that requests made using DRF's Browsable API weren't being logged - but that was on me, as only requests with "application/json" content-type response are.)

The issue here with DRF_API_LOGGER_STATUS_CODES was the exact issue I faced. Converting these to integers instead of strings fixed this for me.

@vishalanandl177 Could you please update the docs to reflect this, as it will be very helpful for others in the future :-)