From 94c394d152529760f2b2e039d0d14641c3d6cfb1 Mon Sep 17 00:00:00 2001 From: ngovinh2k2 Date: Fri, 3 Jul 2026 10:31:57 +0700 Subject: [PATCH] feat: implement django silk for api performance monitoring and profiling --- bootstrap_service/settings.py | 21 +++++++++++++++++++++ bootstrap_service/urls.py | 6 ++++++ requirements.txt | 3 ++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/bootstrap_service/settings.py b/bootstrap_service/settings.py index ab778bb..4212eea 100644 --- a/bootstrap_service/settings.py +++ b/bootstrap_service/settings.py @@ -36,6 +36,7 @@ DJANGO_SETTINGS_MODULE = "bootstrap_service.settings" ROOT_URLCONF = "bootstrap_service.urls" +SILK_ENABLED = os.getenv("ENV", "dev").lower() == "dev" DEBUG = True ALLOWED_HOSTS = ["*"] @@ -113,6 +114,9 @@ ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" +if SILK_ENABLED: + INSTALLED_APPS.append("silk") + # Middleware configuration (required for admin application) MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", @@ -124,6 +128,23 @@ "django.middleware.clickjacking.XFrameOptionsMiddleware", ] +if SILK_ENABLED: + MIDDLEWARE.insert(2, "silk.middleware.SilkyMiddleware") + + def silky_intercept_func(request): + return request.path.startswith("/api/") + + SILKY_INTERCEPT_FUNC = silky_intercept_func + SILKY_AUTHENTICATION = False + SILKY_AUTHORISATION = False + SILKY_PYTHON_PROFILER = True + SILKY_PYTHON_PROFILER_BINARY = False + SILKY_MAX_REQUEST_BODY_SIZE = 1024 + SILKY_MAX_RESPONSE_BODY_SIZE = 0 + SILKY_META = True + SILKY_INTERCEPT_PERCENT = 10 + SILKY_MAX_RECORDED_REQUESTS_CHECK_PERCENT = 10 + # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = "en-us" diff --git a/bootstrap_service/urls.py b/bootstrap_service/urls.py index c48efcf..47edc4a 100644 --- a/bootstrap_service/urls.py +++ b/bootstrap_service/urls.py @@ -14,6 +14,7 @@ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ +from django.conf import settings from django.contrib import admin from django.db import connection from django.http import HttpResponse @@ -48,6 +49,11 @@ def health_check(_): schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui", ), + *( + [path("silk/console/", include("silk.urls", namespace="silk"))] + if settings.SILK_ENABLED + else [] + ), # health path("bootstrap/api/health", health_check), # admin diff --git a/requirements.txt b/requirements.txt index f622631..ba1f2eb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,4 +16,5 @@ pika==1.3.2 django-redis==5.4.0 boto3==1.37.13 psycopg2-binary==2.9.9 -django_tenants==3.6.1 \ No newline at end of file +django_tenants==3.6.1 +django-silk==5.3.2 \ No newline at end of file