How to access incoming requests at Uvicorn level in a FastAPI app and log them?

Viewed 481

I have a FastAPI application that I have deployed using the UVICORN server. My requirement is such that I have to log every incoming request at the UVICORN level and also decode JWT Token that the header of incoming request contains, log that too, at the UVICORN level.

I have been trying to understand the UVICORN library and understanding the code. So far, this is what I have found from their GitHub rep:

https://github.com/encode/uvicorn/blob/df8b49f6779b9de508416ad3823bac868bb8efcf/uvicorn/protocols/http/httptools_impl.py#L128-L138 (code below)

 def data_received(self, data): 
     self._unset_keepalive_if_required() 
  
     try: 
         self.parser.feed_data(data) 
     except httptools.HttpParserError as exc: 
         msg = "Invalid HTTP request received." 
         self.logger.warning(msg, exc_info=exc) 
         self.transport.close() 
     except httptools.HttpParserUpgrade: 
         self.handle_upgrade() 

With some hit & trial, I found that the data parameter this function receives contains all the incoming request payload as a byte string. But I am still not able to locate the exact place where I can find the incoming request and its data.

Where can I find all incoming requests and go about my logging? I don't want to monkey-patch the UVICORN code, I am looking for a sane way to achieve the purpose.

0 Answers
Related