35. Parse Log Lines into Records
Difficulty: Easy · Topic: Data wrangling
Application logs look like 2026-01-05T10:00:01 ERROR [api] timeout after 30s: a timestamp, a level, a service in square brackets, then the message. Write parse_logs(lines) returning a list of dicts with keys ts, level, service and message.
- Levels may be written in any case; return them in upper case. Only
DEBUG,INFO,WARNandERRORare levels. - Fields are separated by one or more spaces; the message is everything after the service, with surrounding spaces removed (it may be empty).
- Skip lines that do not match this shape.
Your code runs in CPython on our servers against 4 tests, including hidden ones.
Sample test
parse_logs(["2026-01-05T10:00:01 ERROR [api] timeout after 30s", "garbage", "2026-01-05T10:00:02 info [db] connected"])Expected: [{'ts': '2026-01-05T10:00:01', 'level': 'ERROR', 'service': 'api', 'message': 'timeout after 30s'}, {'ts': '2026-01-05T10:00:02', 'level': 'INFO', 'service': 'db', 'message': 'connected'}]
Hints
Hint 1
One regular expression with named groups reads all four fields:(?P<ts>\S+) and so on.Hint 2
Match the level with there.IGNORECASE flag, then call .upper().Hint 3
m.groupdict() turns a match into a dict.Learn the concepts
- Wrangling data without pandas · 5 min read. Parse, flatten, deduplicate, join and aggregate in plain Python, with SQL's null rules.
More Python problems
- Reformat Date Strings · Easy
- CSV Rows to Typed Records · Easy
- Flatten Nested JSON · Medium
- Keep the Latest Record per Key · Medium
- Group and Aggregate without pandas · Medium
- Left Join Two Lists of Dicts · Medium
- Merge Overlapping Sessions · Hard
- Schema Validation with a Dead-Letter Queue · Hard