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.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate