OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

how to log request id in django middleware?

  • Thread starter Thread starter Cherrymelon
  • Start date Start date
C

Cherrymelon

Guest
I write some code as below,but it raise an exception

here is request_id_middleware.py

Code:
import uuid

from django.middleware.common import CommonMiddleware
from taiji.logger import logger

class RequestIDMiddleware(CommonMiddleware):
    # pass
    def process_request(self, request):
        request.META['request_id'] = str(uuid.uuid4())
        logger.info(f"start request id: {request.META['request_id']}")
        return request

    def process_response(self, request, response):
        if request.META.get('request_id') is None:
            response.headers['X-REQUEST-ID'] = request.META['request_id']
            logger.info(f"finish request id: {response.headers['X-REQUEST-ID']}")
        return response

logger.py

Code:
import logging


def set_logger(name):
    logger=logging.getLogger(name)
    handler=logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    fmt=logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(fmt)
    logger.addHandler(handler)
    return logger

logger=set_logger('gg')

views

Code:
def index(request: HttpRequest):
    logger.info("hello world")
    return JsonResponse("hello world")

but it tell me

Code:
Traceback (most recent call last):
  File "E:\miniconda\envs\py312\Lib\wsgiref\handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\miniconda\envs\py312\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
    return self.application(environ, start_response)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\wsgi.py", line 124, in __call__
    response = self.get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\base.py", line 141, in get_response
    response._resource_closers.append(request.close)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'WSGIRequest' object has no attribute '_resource_closers'
[20/Apr/2024 22:32:59] "GET /index/ HTTP/1.1" 500 59

is it right way to implement a middleware? why it call a WSGIRequest error? it should be a respone-like object error Any help will be appreciate
<p>I write some code as below,but it raise an exception</p>
<p>here is request_id_middleware.py</p>
<pre class="lang-py prettyprint-override"><code>import uuid

from django.middleware.common import CommonMiddleware
from taiji.logger import logger

class RequestIDMiddleware(CommonMiddleware):
# pass
def process_request(self, request):
request.META['request_id'] = str(uuid.uuid4())
logger.info(f"start request id: {request.META['request_id']}")
return request

def process_response(self, request, response):
if request.META.get('request_id') is None:
response.headers['X-REQUEST-ID'] = request.META['request_id']
logger.info(f"finish request id: {response.headers['X-REQUEST-ID']}")
return response
</code></pre>
<p>logger.py</p>
<pre class="lang-py prettyprint-override"><code>import logging


def set_logger(name):
logger=logging.getLogger(name)
handler=logging.StreamHandler()
handler.setLevel(logging.DEBUG)
fmt=logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(fmt)
logger.addHandler(handler)
return logger

logger=set_logger('gg')
</code></pre>
<p>views</p>
<pre class="lang-py prettyprint-override"><code>def index(request: HttpRequest):
logger.info("hello world")
return JsonResponse("hello world")
</code></pre>
<p>but it tell me</p>
<pre><code>Traceback (most recent call last):
File "E:\miniconda\envs\py312\Lib\wsgiref\handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\miniconda\envs\py312\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
return self.application(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\wsgi.py", line 124, in __call__
response = self.get_response(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\base.py", line 141, in get_response
response._resource_closers.append(request.close)
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'WSGIRequest' object has no attribute '_resource_closers'
[20/Apr/2024 22:32:59] "GET /index/ HTTP/1.1" 500 59
</code></pre>
<p>is it right way to implement a middleware?
why it call a WSGIRequest error? it should be a respone-like object error
Any help will be appreciate</p>
 
Top