Split a log line into its parts
Problem statement
A log line usually has a fixed structure at the start, a date, a time, a level, then a free-form message that can contain any number of spaces of its own: 2024-01-15 10:23:45 ERROR Database connection failed. Splitting on every space would break the message itself into separate words, losing the boundary between "where the fields end" and "where the message begins."
Common mistake: splitting on every space with no limit.
Wrong: line.split(" ")# โ ["2024-01-15", "10:23:45", "ERROR", "Database", "connection", "failed"]That gives six pieces instead of four, the message has been shredded into individual words. The fix is telling the split to stop after the first three spaces, so everything left over stays together as one message field.
Your task: given line = "2024-01-15 10:23:45 ERROR Database connection failed", split it into date, time, level, and message, then print each on its own line.
Expected output:
2024-01-1510:23:45ERRORDatabase connection failedApproach
The idea is the same everywhere: split on spaces, but only three times, so the fourth piece keeps every space that's left.
- Python's
.split(" ", 3)takes amaxsplitargument directly, stopping after 3 splits and leaving the rest as one final piece. - Java's
.split(" ", 4)takes alimit, the maximum number of pieces to return, so4here means "split at most 3 times." - C++ has no built-in limited split, so it's done manually: find the first three spaces with
.find(), and take everything after the third one as the message in one.substr()call.
line = "2024-01-15 10:23:45 ERROR Database connection failed"
date, time, level, message = line.split(" ", 3)
print(date)
print(time)
print(level)
print(message)