This repository has been archived by the owner on Feb 15, 2024. It is now read-only.
forked from ljyanesm/dtool-lookup-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsgi.py
54 lines (43 loc) · 1.65 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
"""Create dserver wsgi debug app.
Environment variable
- DUMP_HTTP_REQUESTS=True
dumps all http requests.
- LOGLEVEL=DEBUG
dumps all debug messages
"""
import logging
import os
import pprint
from dserver import create_app
LOGLEVELS_STR = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET']
LOGLEVELS_INT = [getattr(logging, level) for level in LOGLEVELS_STR]
loglevel = os.getenv("LOGLEVEL", 'ERROR').upper()
if loglevel in LOGLEVELS_STR:
print(f"Select loglevel by keyword {loglevel}.")
loglevel = getattr(logging, loglevel)
elif int(loglevel) in LOGLEVELS_INT:
print(f"Select loglevel by value {loglevel}.")
loglevel = int(loglevel)
else:
print(f"Select default loglevel.")
loglevel = None
if loglevel is not None:
print(f"Set loglevel={loglevel}.")
logging.basicConfig(level=loglevel)
logger = logging.getLogger()
logger.setLevel(loglevel) # modify root logger as well in case it's been set up already elsewhere
app = create_app()
# wrap logging middleware if DUMP_HTTP_REQUESTS set true
if os.getenv("DUMP_HTTP_REQUESTS", 'False').lower() in ('true', '1', 't'):
class LoggingMiddleware:
"""Wrap wsgi app and dump all requests."""
def __init__(self, app):
self._app = app
def __call__(self, env, resp):
errorlog = env['wsgi.errors']
pprint.pprint(('REQUEST', env), stream=errorlog)
def log_response(status, headers, *args):
pprint.pprint(('RESPONSE', status, headers), stream=errorlog)
return resp(status, headers, *args)
return self._app(env, log_response)
app = LoggingMiddleware(app)