-
Notifications
You must be signed in to change notification settings - Fork 1
/
access_log_parser.py
56 lines (45 loc) · 1.5 KB
/
access_log_parser.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
import sys
import json
import httpagentparser
from apachelogs import LogParser
class AccessLogParser:
def __init__(self):
self.log_parser = LogParser(
"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""
)
def parse(self, event):
output = self.log_parser.parse(event)
row = {
"host": output.remote_host,
"time": output.request_time,
**output.headers_in,
**output.directives
}
method, url, protocol = row["%r"].split(" ")
row |= {"method": method, "url": url, "protocol": protocol}
agent_parts = httpagentparser.detect(row["User-Agent"])
row |= agent_parts
self.drop_fields(row)
self.rename_fields(row)
return row
FIELDS_TO_DROP = ["%l", "%u", "%{Referer}i", "%{User-Agent}i", "%r"]
def drop_fields(self, row):
for key in self.FIELDS_TO_DROP:
row.pop(key)
OLD_NEW = {
"%>s": "status",
"%h": "remoteHostName",
"%b": "responseBytes",
"%t": "ts",
"Referer": "referer",
"User-Agent": "userAgent"
}
def rename_fields(self, row):
for old, new in self.OLD_NEW.items():
row[new] = row.pop(old)
if __name__ == "__main__":
access_log_parser = AccessLogParser()
for line in sys.stdin:
message = json.loads(line)
parsed_message = access_log_parser.parse(message)
print(json.dumps(parsed_message, default=str))