Editor

Find Error Patterns

Advanced · Write the code · from Build a Log File Parser That Finds Errors and Patterns

From the lesson: Step 4: Find Time-Based Patterns

Patterns in log data often reveal the root cause of problems. If errors cluster around the same time, it usually means a single event caused multiple failures. Let's analyze error timing to find these clusters.

Read this part of the lesson

Write a function find_error_bursts(log_text, window_minutes=5) that:

1. Parses all ERROR and CRITICAL entries with their timestamps

2. Groups errors that occur within window_minutes of each other into "bursts"

3. Returns a list of bursts, where each burst is a dict with:

- start_time: timestamp of the first error in the burst

- end_time: timestamp of the last error in the burst

- count: number of errors in the burst

- messages: list of error messages

Print each burst found. A burst is a group where each consecutive error is within the window of the previous one.

import re
from datetime import datetime, timedelta
def parse_log_line(line):
pattern = r'(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+) (.+)'
match = re.match(pattern, line)
if not match:
return None
date, time, level, message = match.groups()
return {'date': date, 'time': time, 'level': level, 'message': message}
def find_error_bursts(log_text, window_minutes=5):
# Your code here
pass
log_text = """2024-03-15 08:23:01 INFO Server started
2024-03-15 08:30:45 ERROR Cache connection failed
2024-03-15 08:30:46 ERROR Retry attempt 1 failed
2024-03-15 08:30:48 ERROR Retry attempt 2 failed
2024-03-15 09:45:00 ERROR Database timeout
2024-03-15 10:05:22 ERROR Backup failed
2024-03-15 10:05:23 CRITICAL Disk space critical
2024-03-15 12:00:00 INFO Health check passed"""
bursts = find_error_bursts(log_text)
for i, burst in enumerate(bursts, 1):
print(f'Burst {i}: {burst["count"]} errors from {burst["start_time"]} to {burst["end_time"]}')
for msg in burst['messages']:
print(f' - {msg}')

More Log Parser exercises

All Python exercises · 50 practice problems · Practical Projects quiz