Parse Log Lines
Advanced · Write the code · from Build a Log File Parser That Finds Errors and Patterns
From the lesson: Step 1: Parse Log Lines with Regex
Log files follow a standard format. Each line typically has a timestamp, a severity level (INFO, WARNING, ERROR, CRITICAL), and a message. Here's what real log lines look like:
Read this part of the lessonWrite a function parse_log_line(line) that:
1. Uses regex to parse a log line into its components
2. Returns a dictionary with keys: date, time, level, message
3. Returns None if the line doesn't match the expected format
The log format is: YYYY-MM-DD HH:MM:SS LEVEL Message text
Then parse the provided sample lines and print each parsed result.
import re
def parse_log_line(line):
# Your code here
pass
test_lines = [
'2024-03-15 08:23:01 INFO Server started on port 8080',
'2024-03-15 08:30:45 ERROR Failed to connect to cache server',
'This is not a valid log line',
'2024-03-15 10:05:23 CRITICAL System running low on disk space',
]
for line in test_lines:
result = parse_log_line(line)
if result:
print(f'[{result["level"]}] {result["date"]} {result["time"]} - {result["message"]}')
else:
print(f'SKIPPED: {line}')
More Log Parser exercises
- Count Log LevelsAdvanced
- Classify Errors by TypeAdvanced
- Find Error PatternsAdvanced
- Generate Error SummaryAdvanced
- The Complete LogParser ClassAdvanced
All Python exercises · 50 practice problems · Practical Projects quiz