-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.py
More file actions
59 lines (44 loc) · 1.77 KB
/
analyzer.py
File metadata and controls
59 lines (44 loc) · 1.77 KB
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
57
58
59
from collections import Counter
import csv
import re
LOG_FILE = "sample.log"
OUTPUT_FILE = "output/log_summary.csv"
def analyze_log_file(file_path):
counts = Counter()
error_messages = []
log_pattern = re.compile(r"^\S+\s+\S+\s+(INFO|WARNING|ERROR)\s+(.*)$")
with open(file_path, "r") as file:
for line in file:
match = log_pattern.match(line.strip())
if match:
level = match.group(1)
message = match.group(2)
counts[level] += 1
if level == "ERROR":
error_messages.append(message)
return counts, Counter(error_messages)
def save_summary_to_csv(counts, error_counter, output_file):
with open(output_file, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Metric", "Value"])
writer.writerow(["INFO Count", counts.get("INFO", 0)])
writer.writerow(["WARNING Count", counts.get("WARNING", 0)])
writer.writerow(["ERROR Count", counts.get("ERROR", 0)])
writer.writerow([])
writer.writerow(["Top Error Message", "Occurrences"])
for error, count in error_counter.most_common(5):
writer.writerow([error, count])
def main():
counts, error_counter = analyze_log_file(LOG_FILE)
print("Log Analysis Summary")
print("--------------------")
print(f"INFO count: {counts.get('INFO', 0)}")
print(f"WARNING count: {counts.get('WARNING', 0)}")
print(f"ERROR count: {counts.get('ERROR', 0)}")
print("\nTop Errors:")
for error, count in error_counter.most_common(5):
print(f"{error} -> {count}")
save_summary_to_csv(counts, error_counter, OUTPUT_FILE)
print(f"\nSummary saved to {OUTPUT_FILE}")
if __name__ == "__main__":
main()