-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsgi.py
64 lines (48 loc) · 1.95 KB
/
wsgi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""WSGI script for running the application."""
import logging
import datetime
from app import app
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("[REST API]")
class LoggingMiddleware:
"""Middleware class for logging incoming requests and outgoing responses."""
def __init__(self, app_handler):
"""
Initialize the LoggingMiddleware.
Parameters:
- app_handler (callable): The application handler.
"""
self.__application = app_handler
def __call__(self, environ, start_response):
"""
Call method to handle the request.
Parameters:
- environ (dict): The WSGI environment.
- start_response (callable): The WSGI start_response function.
Returns:
- result: The response generated by the application.
"""
request_method = environ["REQUEST_METHOD"]
path_info = environ["PATH_INFO"]
logger.debug("Incoming request: %s %s", request_method, path_info)
def _start_response(status, headers, *args):
"""
Custom start_response function to log response status.
Parameters:
- status (str): The HTTP status code.
- headers (list): List of response headers.
- *args: Additional arguments.
Returns:
- result: The result of start_response function.
"""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
remote_addr = environ.get("REMOTE_ADDR", "-")
server_protocol = environ.get("SERVER_PROTOCOL", "-")
log_msg = (
f'- - {remote_addr} - - [{timestamp}] "{request_method} {path_info} '
f'{server_protocol}" {status} -\n'
)
logger.info(log_msg)
return start_response(status, headers, *args)
return self.__application(environ, _start_response)
application = LoggingMiddleware(app)