-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102-log_stats.py
45 lines (37 loc) · 1.4 KB
/
102-log_stats.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
#!/usr/bin/env python3
"""Task 15's module.
"""
from pymongo import MongoClient
def print_nginx_request_logs(nginx_collection):
"""Prints stats about Nginx request logs."""
print("{} logs".format(nginx_collection.count_documents({})))
print("Methods:")
methods = ["GET", "POST", "PUT", "PATCH", "DELETE"]
for method in methods:
req_count = len(list(nginx_collection.find({"method": method})))
print("\tmethod {}: {}".format(method, req_count))
status_checks_count = len(
list(nginx_collection.find({"method": "GET", "path": "/status"}))
)
print("{} status check".format(status_checks_count))
def print_top_ips(server_collection):
"""Prints statistics about the top 10 HTTP IPs in a collection."""
print("IPs:")
request_logs = server_collection.aggregate(
[
{"$group": {"_id": "$ip", "totalRequests": {"$sum": 1}}},
{"$sort": {"totalRequests": -1}},
{"$limit": 10},
]
)
for request_log in request_logs:
ip = request_log["_id"]
ip_requests_count = request_log["totalRequests"]
print("\t{}: {}".format(ip, ip_requests_count))
def run():
"""Provides some stats about Nginx logs stored in MongoDB."""
client = MongoClient("mongodb://127.0.0.1:27017")
print_nginx_request_logs(client.logs.nginx)
print_top_ips(client.logs.nginx)
if __name__ == "__main__":
run()