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 | 8 |
8 from http.server import BaseHTTPRequestHandler, HTTPServer | 9 from http.server import BaseHTTPRequestHandler, HTTPServer |
9 from string import Template | 10 from string import Template |
10 | 11 |
11 # The token used for the headers passed by nginx is: http_ | 12 # The token used for the headers passed by nginx is: http_ |
12 REGEX = '\\$http_[a-z_0-9]+\\b' | 13 REGEX = r'\$http_\w+\b' |
Vasily Kuznetsov
2017/08/14 10:59:56
It's a bit more elegant to use a raw string here:
| |
13 DEFAULT_LOG = '$remote_addr - - [$time_local] "$request" $status $bytes_sent' | 14 DEFAULT_LOG = '$remote_addr - - [$time_local] "$request" $status $bytes_sent' |
14 _lock = threading.Lock() | 15 _lock = threading.Lock() |
15 | 16 |
16 | 17 |
17 class Handler(BaseHTTPRequestHandler): | 18 class Handler(BaseHTTPRequestHandler): |
18 def get_header_values(self): | 19 def get_header_values(self): |
19 values = {} | 20 values = {} |
20 headers = re.findall(REGEX, self.format) | 21 headers = re.findall(REGEX, self.format) |
21 for name in headers: | 22 for name in headers: |
22 new_var = name[6:] | 23 new_var = name[6:].replace('_', '-') |
23 values[name[1:]] = self.headers.get(new_var, '-') | 24 values[name[1:]] = self.headers.get(new_var, '-') |
24 return values | 25 return values |
25 | 26 |
27 def send_simple_response(self, status, response=None): | |
28 self.send_response(status) | |
29 self.end_headers() | |
30 if response is None: | |
31 response = bytes(self.responses[status][0], 'UTF-8') | |
32 self.wfile.write(response) | |
33 | |
26 def write_info(self, args): | 34 def write_info(self, args): |
27 _lock.acquire() | 35 message = Template(self.format).safe_substitute(args) + '\n' |
28 try: | 36 with _lock: |
29 message = Template(self.format) | 37 self.output.write(message) |
30 self.output.write(message.safe_substitute(args)) | |
31 self.output.flush() | 38 self.output.flush() |
32 except Exception as e: | |
33 sys.stderr.write(e) | |
Vasily Kuznetsov
2017/08/14 10:59:56
I've just tested this and it seems to raise a Type
| |
34 finally: | |
35 _lock.release() | |
36 | 39 |
37 def do_POST(self): | 40 def do_POST(self): |
38 status = 200 | 41 status = 200 |
39 content = bytes(self.response, 'UTF-8') | 42 content = bytes(self.response, 'UTF-8') |
40 values = { | 43 values = { |
41 'remote_addr': self.address_string(), | 44 'remote_addr': self.address_string(), |
42 'time_local': self.log_date_time_string(), | 45 'time_local': self.log_date_time_string(), |
43 'request': self.requestline, | 46 'request': self.requestline, |
44 'status': status, | 47 'status': status, |
45 'bytes_sent': len(content), | 48 'bytes_sent': len(content), |
46 } | 49 } |
47 values.update(self.get_header_values()) | 50 values.update(self.get_header_values()) |
48 self.write_info(values) | 51 try: |
49 self.send_response(status) | 52 self.write_info(values) |
50 self.end_headers() | 53 self.send_simple_response(status, content) |
51 self.wfile.write(content) | 54 except: |
55 traceback.print_exc(file=sys.stderr) | |
56 self.send_simple_response(500) | |
52 | 57 |
53 | 58 |
54 if __name__ == '__main__': | 59 if __name__ == '__main__': |
55 parser = argparse.ArgumentParser() | 60 parser = argparse.ArgumentParser() |
56 parser.add_argument('--port', action='store', | 61 parser.add_argument('--port', action='store', |
57 default=8000, type=int, | 62 default=8000, type=int, |
58 nargs='?', | 63 nargs='?', |
59 help='Port to use [default: 8000]') | 64 help='Port to use [default: 8000]') |
60 parser.add_argument('--response', action='store', | 65 parser.add_argument('--response', action='store', |
61 type=str, nargs='?', default='OK', | 66 type=str, nargs='?', default='OK', |
62 help='The response send to the client') | 67 help='The response send to the client') |
63 parser.add_argument('--format', action='store', | 68 parser.add_argument('--format', action='store', |
64 type=str, nargs='?', | 69 type=str, nargs='?', |
65 default=DEFAULT_LOG, | 70 default=DEFAULT_LOG, |
66 help='Format of the log ouput') | 71 help='Format of the log ouput') |
67 parser.add_argument('output', action='store', | 72 parser.add_argument('output', action='store', |
68 type=str, nargs='?', default='-', | 73 type=str, nargs='?', default='-', |
69 help='The file where the logs will be written') | 74 help='The file where the logs will be written') |
70 args = parser.parse_args() | 75 args = parser.parse_args() |
71 if args.output and args.output != '-': | 76 if args.output and args.output != '-': |
72 fh = open(args.output, 'a') | 77 fh = open(args.output, 'a') |
73 else: | 78 else: |
74 fh = sys.stdout | 79 fh = open(sys.stdout.fileno(), 'w', closefd=False) |
75 setattr(Handler, 'output', fh) | |
76 setattr(Handler, 'format', args.format) | |
77 setattr(Handler, 'response', args.response) | |
78 server_address = ('', args.port) | |
79 httpd = HTTPServer(server_address, Handler) | |
80 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) | |
81 httpd.serve_forever() | 86 httpd.serve_forever() |
82 except: | 87 finally: |
83 if args.output != '-': | 88 fh.close() |
84 fh.close() | |
LEFT | RIGHT |