Parse a Log Line
A log line has this shape:
2024-03-05 12:01:07 ERROR [db] Connection lost
It is: a date, a time, a level, a module in square brackets, and then a message that may contain spaces and even square brackets of its own.
Write parse_log(line) that returns a dictionary with the keys "date", "time", "level", "module" (without the brackets) and "message".
Understand the problem
The message can contain spaces, so a plain split is not enough.
What does "a b c d e".split(" ", 3) return?
["a", "b", "c", "d", "e"]["a", "b", "c", "d e"]["a", "b", "c"]
The second argument is maxsplit: at most 3 cuts are made, so you get 4 pieces and the last one keeps the rest of the text, spaces and all. That is exactly what you want for a message.
A line is 2024-03-05 12:01:07 WARN [net] retry [3] failed. What must the "message" be? Type it.
Everything after the module belongs to the message, including the brackets in [3]. Only the first bracketed word is the module.
Write the solution
Return the dictionary. Lines in the tests always follow the shape above.
def parse_log(line):
# Write your code here.
pass
Hint 1: a question to ask yourself
How many pieces come before the message, and how can you cut exactly that many and keep the rest together?
Hint 2: the shape of the answer
line.split(" ", 4) gives date, time, level, module and message. Remove the brackets from the module with strip("[]") or slicing.
Reflect
Solution
def parse_log(line):
date, time, level, module, message = line.strip().split(" ", 4)
return {
"date": date,
"time": time,
"level": level,
"module": module.strip("[]"),
"message": message,
}
Another way: a regular expression with named groups
import re
PATTERN = re.compile(r"(?P<date>\S+) (?P<time>\S+) (?P<level>\S+) \[(?P<module>[^\]]+)\] (?P<message>.*)")
def parse_log(line):
return PATTERN.match(line.strip()).groupdict()
What this tests: split with maxsplit, tuple unpacking, strip with a set of characters, and optionally regular expressions.
maxsplit is the key. Splitting on every space would cut the message into words. Splitting a fixed number of times keeps everything after the fixed fields as one piece.
Unpacking checks the shape for free: if a line has too few fields, the unpacking raises a ValueError, which is a sensible way to reject a bad line.
Cost: O(n) in the length of the line.
What an interviewer might ask next: Some lines are malformed. How should the function behave: raise an error, or return None? What would the callers prefer?
VISIBLE = 3
CASES = [
(('2024-03-05 12:01:07 ERROR [db] Connection lost',), {'date': '2024-03-05', 'time': '12:01:07', 'level': 'ERROR', 'module': 'db', 'message': 'Connection lost'}, 'a normal line'),
(('2024-03-05 12:02:00 WARN [net] retry [3] failed',), {'date': '2024-03-05', 'time': '12:02:00', 'level': 'WARN', 'module': 'net', 'message': 'retry [3] failed'}, 'brackets inside the message'),
(('2023-12-31 23:59:59 INFO [app] ok',), {'date': '2023-12-31', 'time': '23:59:59', 'level': 'INFO', 'module': 'app', 'message': 'ok'}, 'a one-word message'),
(('2024-01-01 00:00:00 DEBUG [cache] a b',), {'date': '2024-01-01', 'time': '00:00:00', 'level': 'DEBUG', 'module': 'cache', 'message': 'a b'}, 'spaces inside the message are kept'),
(('2024-03-05 12:01:07 ERROR [auth-service] token expired at 12:00',), {'date': '2024-03-05', 'time': '12:01:07', 'level': 'ERROR', 'module': 'auth-service', 'message': 'token expired at 12:00'}, 'a module name with a hyphen'),
(('2024-03-05 12:01:07 ERROR [db] Connection lost\n',), {'date': '2024-03-05', 'time': '12:01:07', 'level': 'ERROR', 'module': 'db', 'message': 'Connection lost'}, 'a trailing newline'),
]