Editor

Classify Errors by Type

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

From the lesson: Step 3: Count Errors by Type

Knowing you have 5 errors is useful. Knowing that 3 of them are "connection refused" and 2 are "timeout" is much more useful. Let's classify error messages into types by extracting key phrases.

Read this part of the lesson

Write a function classify_errors(log_text) that:

1. Parses the log and filters for ERROR and CRITICAL entries only

2. Classifies each error into a type based on keywords in the message:

- Connection: message contains "connect" or "connection"

- Timeout: message contains "timeout" or "timed out"

- Authentication: message contains "auth" or "login"

- Disk: message contains "disk" or "space"

- Other: anything that doesn't match

3. Returns a dictionary mapping error types to their count

Print the error types sorted by count.

import re
from collections import Counter
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 classify_errors(log_text):
# Your code here
pass
log_text = """2024-03-15 08:23:01 INFO Server started
2024-03-15 08:30:45 ERROR Failed to connect to cache server
2024-03-15 08:30:46 ERROR Retrying cache connection
2024-03-15 09:45:00 ERROR Database timeout exceeded
2024-03-15 10:05:22 ERROR Backup failed: disk space insufficient
2024-03-15 10:05:23 CRITICAL System running low on disk space
2024-03-15 11:30:15 ERROR Authentication failed for user admin
2024-03-15 11:30:16 ERROR Authentication failed for user admin
2024-03-15 11:45:00 WARNING High memory usage"""
error_types = classify_errors(log_text)
for error_type, count in sorted(error_types.items(), key=lambda x: x[1], reverse=True):
print(f'{error_type}: {count}')

More Log Parser exercises

All Python exercises · 50 practice problems · Practical Projects quiz