Left: | ||
Right: |
LEFT | RIGHT |
---|---|
1 #!/usr/bin/env python3 | 1 #!/usr/bin/env python3 |
2 | 2 |
3 import argparse | 3 import argparse |
4 import re | 4 import re |
5 import sys | 5 import sys |
6 import threading | 6 import threading |
7 import traceback | 7 import traceback |
8 | 8 |
9 from http.server import BaseHTTPRequestHandler, HTTPServer | 9 from http.server import BaseHTTPRequestHandler, HTTPServer |
10 from string import Template | 10 from string import Template |
11 | 11 |
12 # The token used for the headers passed by nginx is: http_ | 12 # The token used for the headers passed by nginx is: http_ |
13 REGEX = r'\$http_[\w]+\b' | 13 REGEX = r'\$http_\w+\b' |
Vasily Kuznetsov
2017/08/15 18:56:25
Square brackets are not necessary around '\w', it
f.lopez
2017/08/16 00:54:31
Done.
| |
14 DEFAULT_LOG = '$remote_addr - - [$time_local] "$request" $status $bytes_sent' | 14 DEFAULT_LOG = '$remote_addr - - [$time_local] "$request" $status $bytes_sent' |
15 _lock = threading.Lock() | 15 _lock = threading.Lock() |
16 | 16 |
17 | 17 |
18 class Handler(BaseHTTPRequestHandler): | 18 class Handler(BaseHTTPRequestHandler): |
19 def get_header_values(self): | 19 def get_header_values(self): |
20 values = {} | 20 values = {} |
21 headers = re.findall(REGEX, self.format) | 21 headers = re.findall(REGEX, self.format) |
22 for name in headers: | 22 for name in headers: |
23 new_var = name[6:] | 23 new_var = name[6:].replace('_', '-') |
24 values[name[1:]] = self.headers.get(new_var, '-') | 24 values[name[1:]] = self.headers.get(new_var, '-') |
25 return values | 25 return values |
26 | 26 |
27 def send_simple_response(self, status, response=None): | 27 def send_simple_response(self, status, response=None): |
28 self.send_response(status) | 28 self.send_response(status) |
29 self.end_headers() | 29 self.end_headers() |
30 if response is None: | 30 if response is None: |
31 response = bytes(self.responses[status][0], 'UTF-8') | 31 response = bytes(self.responses[status][0], 'UTF-8') |
32 self.wfile.write(response) | 32 self.wfile.write(response) |
33 | 33 |
34 def write_info(self, args): | 34 def write_info(self, args): |
35 _lock.acquire() | 35 message = Template(self.format).safe_substitute(args) + '\n' |
36 try: | 36 with _lock: |
37 message = Template(self.format) | 37 self.output.write(message) |
38 self.output.write(message.safe_substitute(args) + '\n') | |
39 self.output.flush() | 38 self.output.flush() |
40 except Exception: | |
Vasily Kuznetsov
2017/08/15 18:56:25
You can just write `except` instead of `except Exc
f.lopez
2017/08/16 00:54:31
Done.
| |
41 traceback.print_exc(file=sys.stderr) | |
42 self.send_simple_response(500) | |
Vasily Kuznetsov
2017/08/15 18:56:25
When `write_info` returns, the code will try to se
f.lopez
2017/08/16 00:54:32
What if I use this function to return the code ins
Vasily Kuznetsov
2017/08/16 11:32:27
Yes, this approach can work too, although you woul
| |
43 finally: | |
44 _lock.release() | |
45 | 39 |
46 def do_POST(self): | 40 def do_POST(self): |
47 status = 200 | 41 status = 200 |
48 content = bytes(self.response, 'UTF-8') | 42 content = bytes(self.response, 'UTF-8') |
49 values = { | 43 values = { |
50 'remote_addr': self.address_string(), | 44 'remote_addr': self.address_string(), |
51 'time_local': self.log_date_time_string(), | 45 'time_local': self.log_date_time_string(), |
52 'request': self.requestline, | 46 'request': self.requestline, |
53 'status': status, | 47 'status': status, |
54 'bytes_sent': len(content), | 48 'bytes_sent': len(content), |
55 } | 49 } |
56 values.update(self.get_header_values()) | 50 values.update(self.get_header_values()) |
57 self.write_info(values) | 51 try: |
58 self.send_simple_response(status, content) | 52 self.write_info(values) |
53 self.send_simple_response(status, content) | |
54 except: | |
55 traceback.print_exc(file=sys.stderr) | |
56 self.send_simple_response(500) | |
59 | 57 |
60 | 58 |
61 if __name__ == '__main__': | 59 if __name__ == '__main__': |
62 parser = argparse.ArgumentParser() | 60 parser = argparse.ArgumentParser() |
63 parser.add_argument('--port', action='store', | 61 parser.add_argument('--port', action='store', |
64 default=8000, type=int, | 62 default=8000, type=int, |
65 nargs='?', | 63 nargs='?', |
66 help='Port to use [default: 8000]') | 64 help='Port to use [default: 8000]') |
67 parser.add_argument('--response', action='store', | 65 parser.add_argument('--response', action='store', |
68 type=str, nargs='?', default='OK', | 66 type=str, nargs='?', default='OK', |
69 help='The response send to the client') | 67 help='The response send to the client') |
70 parser.add_argument('--format', action='store', | 68 parser.add_argument('--format', action='store', |
71 type=str, nargs='?', | 69 type=str, nargs='?', |
72 default=DEFAULT_LOG, | 70 default=DEFAULT_LOG, |
73 help='Format of the log ouput') | 71 help='Format of the log ouput') |
74 parser.add_argument('output', action='store', | 72 parser.add_argument('output', action='store', |
75 type=str, nargs='?', default='-', | 73 type=str, nargs='?', default='-', |
76 help='The file where the logs will be written') | 74 help='The file where the logs will be written') |
77 args = parser.parse_args() | 75 args = parser.parse_args() |
78 if args.output and args.output != '-': | 76 if args.output and args.output != '-': |
79 fh = open(args.output, 'a') | 77 fh = open(args.output, 'a') |
80 else: | 78 else: |
81 fh = sys.stdout | 79 fh = open(sys.stdout.fileno(), 'w', closefd=False) |
82 Handler.output = fh | |
83 Handler.format = args.format | |
84 Handler.response = args.response | |
85 server_address = ('', args.port) | |
86 httpd = HTTPServer(server_address, Handler) | |
87 try: | 80 try: |
81 Handler.output = fh | |
82 Handler.format = args.format | |
83 Handler.response = args.response | |
84 server_address = ('', args.port) | |
85 httpd = HTTPServer(server_address, Handler) | |
88 httpd.serve_forever() | 86 httpd.serve_forever() |
89 except: | 87 finally: |
90 if args.output != '-': | 88 fh.close() |
91 fh.close() | |
LEFT | RIGHT |