Medium: Interview Core · Problem 28 of 82

Parse a Log Line

MediumStringsPython

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?

  1. ["a", "b", "c", "d", "e"]
  2. ["a", "b", "c", "d e"]
  3. ["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?