Parse Log Line

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4

Problem

Each line of a service log reads level, timestamp, then a free-text message, separated by single spaces. What are its three fields, given that the message runs to the end of the line and keeps any spaces it contains?

One line. A dozen fields hidden inside.

Example 1

Input:

line = "ERROR 2024-03-15T09:12:00 Connection timeout"

Output:

{"level":"ERROR","timestamp":"2024-03-15T09:12:00","message":"Connection timeout"}

Example 2

Input:

line = "INFO 2024-01-01T00:00:00 Server started"

Output:

{"level":"INFO","timestamp":"2024-01-01T00:00:00","message":"Server started"}

Worked solution and explanation

This is a fixed-prefix, free-tail parse dressed up as log processing. Two fields are guaranteed single tokens; the third is whatever is left, and it contains the very delimiter you are cutting on. Anyone can pull out the level. The trick is stopping after the second space. Cut at every space and parts[2] is just 'Connection', so every multi-word message is silently trimmed to its first word, and nothing raises to warn you.

Walk it through

Step 1: Cap the cut at two separators

The level and the timestamp never contain a space, so the first two spaces are the only real field boundaries. Every space after them belongs to the message. line.split(' ', 2) stops after two cuts and hands back exactly three pieces, the last one untouched.

Step 2: Name the three pieces

Map the pieces to 'level', 'timestamp' and 'message' in that order. The message piece is the original text byte for byte, so there is nothing to rebuild.

The solution

Bounded split for structured field extraction
def parse_log(line):
    parts = line.split(' ', 2)
    result = {
        'level': parts[0],
        'timestamp': parts[1],
        'message': parts[2]
    }
    return result
Cut at every space
line.split(' ') on the DEBUG line yields seven pieces; parts[2] is 'User' and the other five words vanish. Rejoining parts[2:] recovers the message, at the cost of a second pass and a rebuilt string.
Stop after two
line.split(' ', 2) yields three pieces, and the third is the message exactly as written, internal spaces included. One pass, nothing to reassemble.

Common follow-up questions