@@ -25,6 +25,7 @@ class HttpAccessLogMiddleware(BaseHTTPMiddleware):
2525 has_cf_headers (bool): If True, use cloudflare headers to get http request info. Defaults to False.
2626 debug_format (str ): Http access log debug message format. Defaults to `HttpAccessLogMiddleware._DEBUG_FORMAT`.
2727 msg_format (str ): Http access log message format. Defaults to `HttpAccessLogMiddleware._MSG_FORMAT`.
28+ use_debug_log (bool): If True, use debug log to log http access log. Defaults to True.
2829 """
2930
3031 _DEBUG_FORMAT = '<n>[{request_id}]</n> {client_host} {user_id} "<u>{method} {url_path}</u> HTTP/{http_version}"'
@@ -37,12 +38,14 @@ def __init__(
3738 has_cf_headers : bool = False ,
3839 debug_format : str = _DEBUG_FORMAT ,
3940 msg_format : str = _MSG_FORMAT ,
41+ use_debug_log : bool = True ,
4042 ):
4143 super ().__init__ (app )
4244 self .has_proxy_headers = has_proxy_headers
4345 self .has_cf_headers = has_cf_headers
4446 self .debug_format = debug_format
4547 self .msg_format = msg_format
48+ self .use_debug_log = use_debug_log
4649
4750 async def dispatch (self , request : Request , call_next ) -> Response :
4851 _logger = logger .opt (colors = True , record = True )
@@ -53,6 +56,8 @@ async def dispatch(self, request: Request, call_next) -> Response:
5356 _http_info ["request_id" ] = request .headers .get ("X-Request-ID" )
5457 elif "X-Correlation-ID" in request .headers :
5558 _http_info ["request_id" ] = request .headers .get ("X-Correlation-ID" )
59+
60+ ## Set request_id to request state:
5661 request .state .request_id = _http_info ["request_id" ]
5762
5863 _http_info ["client_host" ] = request .client .host
@@ -161,16 +166,25 @@ async def dispatch(self, request: Request, call_next) -> Response:
161166 if hasattr (request .state , "user_id" ):
162167 _http_info ["user_id" ] = str (request .state .user_id )
163168
164- _debug_msg = self .debug_format .format (** _http_info )
165- # _logger.debug(_debug_msg)
166- await run_in_threadpool (
167- _logger .debug ,
168- _debug_msg ,
169- )
169+ ## Debug log:
170+ if self .use_debug_log :
171+ _debug_msg = self .debug_format .format (** _http_info )
172+ # _logger.debug(_debug_msg)
173+ await run_in_threadpool (
174+ _logger .debug ,
175+ _debug_msg ,
176+ )
177+ ## Debug log
178+
179+ ## Set http info to request state:
180+ request .state .http_info = _http_info
170181
182+ ## Process request:
171183 _start_time = time .time ()
172184 response = await call_next (request )
173185 _http_info ["response_time" ] = round ((time .time () - _start_time ) * 1000 , 1 )
186+ ## Response processed
187+
174188 if "X-Process-Time" in response .headers :
175189 try :
176190 _http_info ["response_time" ] = float (
@@ -208,6 +222,7 @@ async def dispatch(self, request: Request, call_next) -> Response:
208222 "Can not serialize `http_info` to json string in HttpAccessLogMiddleware!"
209223 )
210224
225+ ## Http access log:
211226 _LEVEL = "INFO"
212227 _msg_format = self .msg_format
213228 if _http_info ["status_code" ] < 200 :
@@ -225,7 +240,7 @@ async def dispatch(self, request: Request, call_next) -> Response:
225240 elif 500 <= _http_info ["status_code" ]:
226241 _LEVEL = "ERROR"
227242 _msg_format = (
228- f'<r> { _msg_format .replace ("{status_code}" , "<n>{status_code}</n>" )} </r> '
243+ f'{ _msg_format .replace ("{status_code}" , "<n>{status_code}</n>" )} '
229244 )
230245
231246 _msg = _msg_format .format (** _http_info )
@@ -235,5 +250,6 @@ async def dispatch(self, request: Request, call_next) -> Response:
235250 _LEVEL ,
236251 _msg ,
237252 )
253+ ## Http access log
238254
239255 return response
0 commit comments