Editor

Count Log Levels

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

From the lesson: Step 2: Extract Timestamps and Count by Level

Now that we can parse individual lines, let's process an entire log. We want to parse all lines, count how many of each severity level we have, and identify the time range covered by the log.

Read this part of the lesson

Write a function count_by_level(log_text) that:

1. Splits the log text into lines and parses each one

2. Counts the number of entries per severity level

3. Returns a dictionary with level names as keys and counts as values

4. Skips lines that don't match the log format

Print the counts sorted by count descending.

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 count_by_level(log_text):
# Your code here
pass
log_text = """2024-03-15 08:23:01 INFO Server started
2024-03-15 08:25:12 WARNING High memory usage
2024-03-15 08:30:45 ERROR Cache connection failed
2024-03-15 08:30:46 ERROR Retry failed
2024-03-15 09:15:33 WARNING Slow query detected
2024-03-15 09:45:00 ERROR Database timeout
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"""
counts = count_by_level(log_text)
for level, count in sorted(counts.items(), key=lambda x: x[1], reverse=True):
print(f'{level}: {count}')

More Log Parser exercises

All Python exercises · 50 practice problems · Practical Projects quiz