vishalanandl177 / DRF-API-Logger

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

Admin page is broken after installation #83

Closed fchabouis closed 11 months ago

fchabouis commented 11 months ago

Hello, I followed the instructions given on the readme, but get a broken admin page with the following error:

NoReverseMatch at /admin/

Reverse for 'app_list' with keyword arguments '{'app_label': 'drf_api_logger'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|authtoken|batid)/$']

Additionnal details: I have installed the drf_api_logger extension with pip I have added it in the installed app and as a middleware. I have added in settings.py some flags. I have run the migrations and the drf_api_logs table has been created in the DB.

However, when I make an API call, nothing is logged. The admin page is broken with a NoReverseMatch error.

Here is my settings.py file:

"""
Django settings for app project.

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

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
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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 = os.environ.get("DJANGO_SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(os.environ.get("DEBUG", default=0))

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOST").split(" ")
CSRF_TRUSTED_ORIGINS = os.environ.get("DJANGO_CSRF_TRUSTED_ORIGINS").split(" ")

CORS_ALLOWED_ORIGINS = os.environ.get("DJANGO_CORS_ALLOWED_ORIGINS").split(" ")
CORS_ALLOW_ALL_ORIGINS = True

# log every request made to the API in the database
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

if DEBUG:
    import socket  # only if you haven't already imported this

    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + [
        "127.0.0.1",
        "10.0.2.2",
    ]

    NOTEBOOK_ARGUMENTS = [
        "--ip",
        "0.0.0.0",
        "--allow-root",
        "--no-browser",
    ]  # see https://stackoverflow.com/a/47063057/1892308

# Application definition

INSTALLED_APPS = [
    "debug_toolbar",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "rest_framework.authtoken",
    "django.contrib.postgres",
    "corsheaders",
    "batid",
    "website",
    "api_alpha",
    "xp",
    "django_extensions",
    "drf_api_logger",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware",
]

ROOT_URLCONF = "app.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "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 = "app.wsgi.application"

STATIC_ROOT = os.path.join(BASE_DIR, "static")

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

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("DJANGO_SQL_ENGINE"),
        "NAME": os.environ.get("POSTGRES_NAME"),
        "USER": os.environ.get("POSTGRES_USER"),
        "PASSWORD": os.environ.get("POSTGRES_PASSWORD"),
        "HOST": os.environ.get("POSTGRES_HOST"),
        "PORT": os.environ.get("POSTGRES_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",
    },
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication"
    ],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 30,
}

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

# 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/"

CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL")
CELERY_BACKEND_URL = os.environ.get("CELERY_RESULT_BACKEND")

# Bat ID custom settings
DEFAULT_SRID = int(os.environ.get("DEFAULT_SRID"))  # 2154 = Lambert 93
MIN_BDG_AREA = float(os.environ.get("MIN_BDG_AREA"))

# Zoom range for vector tiles generation
VCTR_TILES_MIN_ZOOM = 14
VCTR_TILES_MAX_ZOOM = 18

sentry_dsn = os.environ.get("SENTRY_DSN", None)
if sentry_dsn:
    sentry_sdk.init(
        dsn=sentry_dsn,
        integrations=[
            DjangoIntegration(),
        ],
        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,
        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True,
        environment=os.environ.get("SENTRY_ENV"),
    )

Is there anything obvious I'm missing? Thanks!

fchabouis commented 11 months ago

The admin panel error appears as soon as I set DRF_API_LOGGER_DATABASE = True. If I set it to False, I can access the admin page, but there is no information related to drf_api_logger.

vishalanandl177 commented 11 months ago

Did you migrate after setting to DRF_API_LOGGER_DATABASE = True?

fchabouis commented 11 months ago

I don't rememeber if I migrated after or before setting DRF_API_LOGGER_DATABASE.

I have tried drf-api-tracking instead and got the same problem with the admin page, so I knew the problem with the admin page was not coming from your package.

Finally I found that one of my previously installed_app was somehow preventing me from adding an app that was adding something on the admin page.

The solution for me was to add drf_api_logger in the INSTALLED_APP before the problematic application in the list. I didn't know the order of the list was important.

As I finally found the solution while playing with the other plugin, I will stick with the other one. But thank you for your answer, and I hope this issue will help if someone encounters the same problem.

Have a good day!