Skip to content

Add CID to the uwsgi proxy while running django in production #72

@anuj9196

Description

@anuj9196

Using uWSGI in the production to run application inside the docker container.

I have added the following log format

UWSGI_LOG_FORMAT='[pid: %(pid)|app: %(wid)|req: %(rlen)/%(total_requests)] %(addr) () {%(vars) vars in %(cl) bytes} [%(ltime)] %(method) %(uri) => generated %(size) bytes in %(msecs) msecs (%(protocol)) %(headers) (cid:%(var.CID))'

and crated a uwsgi wrapper middleware

from cid.locals import get_cid


class UWSGICIDMiddleware:
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        try:
            import uwsgi
            cid = (
                    environ.get("HTTP_X_CORRELATION_ID") or
                    environ.get("HTTP_X_REQUEST_ID") or
                    environ.get("REQUEST_ID") or
                    get_cid() or
                    "-"  # fallback
            )
            uwsgi.set_logvar("CID", cid)
        except ImportError:
            pass
        return self.app(environ, start_response)

which we are using in the wsgi.py configuration as

import os

from django.core.wsgi import get_wsgi_application

from tools.proxy.uwsgi import UWSGICIDMiddleware

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedal.settings')

application = UWSGICIDMiddleware(get_wsgi_application())

However, the log statement does not contain the cid, but the application has cid added to every log

feedal__dev__app            | {"asctime": "2025-06-26 20:10:01,668", "levelname": "INFO", "name": "app", "module": "views", "funcName": "post", "lineno": 34, "message": "types: ['count_stats', 'by_country', 'by_device', 'by_device_type', 'by_os', 'by_browser', 'by_referrer', 'by_location', 'visits_and_responses', 'engagement_metrics']", "cid": "4bce305b-dba1-47dd-bda9-d06b194278ec"}
feedal__dev__app            | /app/analytics/analytics.py:58: UserWarning: DataFrame columns are not unique, some columns will be omitted.
feedal__dev__app            |   .to_dict(orient='records')
feedal__dev__app            | [pid: 18|app: 1|req: -/-] 192.168.65.1 () {58 vars in 50 bytes} [26/Jun/2025:20:10:00 +0530] POST /analytics/form/?type=count_stats%2Cby_country%2Cby_device%2Cby_device_type%2Cby_os%2Cby_browser%2Cby_referrer%2Cby_location%2Cvisits_and_responses%2Cengagement_metrics => generated 1334 bytes in 1962 msecs (-) 10 (cid:-)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions