Codzy

Automation: analysing logs

Servers write everything they do into logs: thousands of lines a day. Nobody reads them by hand: a script analyses them, counts errors, finds the failing pages and sends an alert.

Regular expressions (re.findall) extract the useful bits of each line; collections.Counter counts them. With re.MULTILINE, ^ and $ mean the start and end of each line. 5xx codes (500, 503…) are server errors: those are the ones to watch first.

import re
from collections import Counter

log = """2026-11-15 10:02 INFO  user=lina action=login
2026-11-15 10:05 ERROR user=omar action=pay
2026-11-15 10:07 INFO  user=omar action=login"""

levels = Counter(re.findall(r"\b(INFO|ERROR|WARNING)\b", log))
users = re.findall(r"user=(\w+)", log)
print(levels)
print(sorted(set(users)))

Start the lesson