Editor

The Complete LogParser Class

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

From the lesson: Step 6: Build the Complete LogParser Class

Now let's wrap everything into a reusable class. A LogParser class gives us a clean interface: load the logs once, then call different analysis methods as needed. This is how professional log analysis tools are structured.

Read this part of the lesson

Build a LogParser class with:

`__init__(self, log_text)`: Parse all lines and store the entries as a list of dicts.

`level_counts(self)`: Return a dict of level -> count.

`errors_only(self)`: Return a list of only ERROR and CRITICAL entries.

`most_common_error(self)`: Return a tuple of (message, count) for the most frequent error.

`report(self)`: Print a formatted summary report showing total entries, level breakdown, error count, and most common error.

Test it with the provided log data.

import re
from collections import Counter
class LogParser:
def __init__(self, log_text):
# Parse all lines and store entries
pass
def _parse_line(self, 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 level_counts(self):
# Return dict of level -> count
pass
def errors_only(self):
# Return list of ERROR and CRITICAL entries
pass
def most_common_error(self):
# Return (message, count) tuple
pass
def report(self):
# Print formatted report
pass
log_text = """2024-03-15 08:23:01 INFO Server started on port 8080
2024-03-15 08:25:12 WARNING High memory usage: 85%
2024-03-15 08:30:45 ERROR Failed to connect to cache server
2024-03-15 08:30:46 ERROR Failed to connect to cache server
2024-03-15 09:15:33 WARNING Slow query detected
2024-03-15 09:45:00 ERROR Database timeout exceeded
2024-03-15 10:00:01 INFO Backup started
2024-03-15 10:05:23 CRITICAL Disk space critical
2024-03-15 12:00:00 INFO Health check passed"""
parser = LogParser(log_text)
parser.report()

More Log Parser exercises

All Python exercises · 50 practice problems · Practical Projects quiz