Skip to content

Commit 82e78be

Browse files
author
Eliad hershkovitz
committed
Improvements
1) Fix standard formatter 2) misc refactoring
1 parent c3e26b9 commit 82e78be

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

requestlogger/__init__.py

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -37,29 +37,44 @@ def __init__(self, application, handlers, formatter=None, propagate=True, ip_hea
3737
self.logger.addHandler(handler)
3838
self.ip_header = ip_header
3939
self.application = application
40+
self._status_code = ''
41+
self._content_length = 0
4042

4143
def __call__(self, environ, start_response):
4244
start = clock()
43-
status_codes = []
44-
content_lengths = []
4545

46-
def custom_start_response(status, response_headers, exc_info=None):
47-
status_codes.append(int(status.partition(' ')[0]))
46+
def _start_response(status, response_headers, exc_info=None):
47+
self._status_code = status.split()[0]
48+
self._content_length = 0
4849
for name, value in response_headers:
49-
if name.lower() == 'content-length':
50-
content_lengths.append(int(value))
51-
break
52-
return start_response(status, response_headers, exc_info)
53-
retval = self.application(environ, custom_start_response)
50+
if name.lower() == 'content-length':
51+
self._content_length += int(value)
52+
break
53+
return start_response(status, response_headers, exc_info)
54+
55+
retval = self.application(environ, _start_response)
5456
runtime = int((clock() - start) * 10**6)
55-
content_length = content_lengths[0] if content_lengths else len(b''.join(retval))
56-
msg = self.formatter(status_codes[0], environ, content_length, ip_header=self.ip_header, rt_us=runtime)
57+
msg = self.formatter(self._status_code, environ, self._content_length, ip_header=self.ip_header, rt_us=runtime)
5758
self.logger.info(msg)
5859
return retval
5960

61+
62+
6063
@staticmethod
61-
def standard_formatter(status_code, environ, content_length):
62-
return "{0} {1}".format(dt.now().isoformat(), status_code)
64+
def standard_formatter(status_code, environ, content_length, **kwargs):
65+
_host = environ.get('REMOTE_ADDR', '')
66+
_timestamp = dt.now(Local).strftime("%d/%b/%Y:%H:%M:%S %z")
67+
_request = "{0} {1}{2}{3} {4}".format(
68+
environ.get('REQUEST_METHOD', ''),
69+
environ.get('PATH_INFO', ''),
70+
'?' if environ.get('QUERY_STRING', '') else '',
71+
environ.get('QUERY_STRING', ''),
72+
environ.get('SERVER_PROTOCOL', '')
73+
)
74+
_status = status_code
75+
_size = content_length
76+
77+
return f'{_host} - - [{_timestamp}] "{_request}" {_status} {_size}'
6378

6479

6580
def ApacheFormatter(with_response_time=True):

0 commit comments

Comments
 (0)