Write a script that tails a log file and counts error types every 60 seconds.

AdvancedHands-onPython for DevOps
Answer
import re
import time
from collections import Counter

PATTERN = re.compile(r"ERROR\s+\[(?P<kind>[\w.]+)\]")

def follow(path):
    with open(path) as f:
        f.seek(0, 2)                      # start at end of file
        while True:
            line = f.readline()
            if not line:
                time.sleep(0.5)
                yield None
                continue
            yield line

counts, window_start = Counter(), time.time()
for line in follow("/var/log/app/app.log"):
    if line and (m := PATTERN.search(line)):
        counts[m["kind"]] += 1
    if time.time() - window_start >= 60:
        print(time.strftime("%H:%M"), dict(counts.most_common(5)))
        counts.clear()
        window_start = time.time()

Key trick → The generator yields None when idle so the 60-second window still flushes during quiet periods. Compile the regex once outside the loop.

All Real-World Interview questions Roadmap: Interview readiness

More on Python for DevOps