Generator-Based Parser for Structured Log Streams
StringsModel answerLast updated
Build a memory-efficient Python generator that parses log records with timestamps and key-value pairs, handling quoted strings with escapes.
You are building a log ingestion pipeline for distributed systems that produce structured text logs. Each log record occupies one line and follows this format:
<timestamp> <key1>=<value1> <key2>=<value2> ...
Your task is to implement a Python function that reads a log file and yields each parsed record as a dictionary. Because log files in production environments can reach many gigabytes, your implementation must stream the file using a generator—never loading the entire file into memory.
Record Structure
Each line begins with a timestamp, followed by zero or more key-value pairs.
Timestamp
The timestamp appears first and takes one of two forms:
- ISO format without spaces:
2025-03-14T08:22:15Z - Date and time with a space:
2025-03-14 08:22:15.123
Store the timestamp unchanged in the output dictionary under the key 'timestamp'.
Key-Value Pairs
Each pair consists of a key, an equals sign, and a value.
Key format: one or more characters from the set [A-Za-z0-9_.-], immediately followed by =.
Value format: either unquoted or quoted.
-
Unquoted: no whitespace, ends at the next space/tab or end of line. Example:
device=sensor-42orcount=157. -
Quoted: surrounded by double quotes. May contain:
- Spaces (including multiple consecutive spaces)
- Equals signs (e.g.,
config="mode=auto") - Escaped double quotes written as
\"(the backslash-quote sequence represents a literal quote character)
The output removes the outer quotes and converts escape sequences to their literal characters.
-
Empty:
field=""produces{'field': ''}.
Separators: one or more spaces or tabs between consecutive pairs.
Blank lines: skip lines that are empty or contain only whitespace.
Examples
Basic example with mixed value types:
Input: 2025-03-14T08:22:15Z device=sensor-42 status="system ready" code=200 attempts=1
Output: {'timestamp': '2025-03-14T08:22:15Z', 'device': 'sensor-42', 'status': 'system ready', 'code': '200', 'attempts': '1'}
Timestamp with space, and quoted value containing multiple spaces:
Input: 2025-03-14 08:22:16.890 device=gateway-7 address=10.0.0.5 error="connection timeout: retry limit exceeded" severity=high
Output: {'timestamp': '2025-03-14 08:22:16.890', 'device': 'gateway-7', 'address': '10.0.0.5', 'error': 'connection timeout: retry limit exceeded', 'severity': 'high'}
Escaped quotes, inner equals, and empty value:
Input: 2025-03-14T08:22:18Z action="config update" params="format=\"json\" compress=true" comment=""
Output: {'timestamp': '2025-03-14T08:22:18Z', 'action': 'config update', 'params': 'format="json" compress=true', 'comment': ''}
Requirements
- Implement a generator function that yields one dictionary per valid line
- Do not use
file.read()orfile.readlines()—iterate line by line to keep memory usage constant - Return all values as strings (do not parse numbers or convert timestamps)
- Skip blank lines silently
Questions to Consider
- How should your parser handle malformed input (unterminated quotes, missing timestamps, invalid escape sequences)?
- If a key appears multiple times in one line, which value should the output contain?
- What escape sequences beyond
\"should be supported, and how should unknown escapes be treated? - What happens if a field is named
timestamp—does it overwrite the line's timestamp? - Should
key=with nothing after the equals produce an empty string or be treated as invalid? - What text encoding should be assumed, and how should decoding errors be handled?
Hints
Hint 1
Start by identifying where the timestamp ends—look for the first equals sign to find where key-value pairs begin.
Hint 2
A simple state machine with 'scanning key', 'scanning unquoted value', and 'inside quoted value' states handles most parsing edge cases cleanly.
Hint 3
Use a generator with 'yield' inside a loop over the file object to ensure constant memory usage regardless of file size.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building a line-oriented parser that handles three challenges: extracting timestamps that may contain spaces, tokenizing key-value pairs with quoted values, and streaming large files without loading them entirely into memory.
Timestamp Extraction
The timestamp occupies the start of each line and takes one of two forms: ISO format without spaces (2025-03-14T08:22:15Z) or a date-time pair separated by one space (2025-03-14 08:22:15.123). A reliable approach is to scan for the first = character, which marks the beginning of the first key-value pair. Everything before that first = (excluding trailing whitespace) forms the timestamp region. If the timestamp contains a space, we keep it; if not, we keep the single token.
Tokenization Strategy
Two main approaches exist: regular expressions and character-by-character scanning.
Regular expressions can match key-value patterns but become complex when handling nested quotes and escapes. A regex like (\w+)=("(?:[^"\\]|\\.)*"|[^\s]+) captures most cases but requires careful construction and testing.
Character-by-character scanning uses a simple state machine:
- Scanning for key: accumulate alphanumerics, underscores, dots, hyphens until
= - After
=: check if the next character is"(quoted) or not (unquoted) - Unquoted value: accumulate until whitespace or end of line
- Quoted value: accumulate characters, handling
\"escapes, until the closing"
The state machine approach makes escape handling explicit and avoids regex backtracking on long quoted strings.
Memory Efficiency
Python file objects are iterable and yield one line at a time when used in a for loop. Wrapping this in a generator function with yield ensures that only one line resides in memory at any moment, regardless of file size. Calling file.read() or file.readlines() would load the entire file and violate the memory constraint.
Edge Cases and Policy Decisions
Malformed lines: A production parser should decide whether to skip invalid lines, raise exceptions, or log warnings. For this implementation, skipping malformed lines silently keeps the pipeline robust.
Duplicate keys: If a key appears twice, the last occurrence wins (matching Python dict update behavior).
Escape sequences: Only \" is specified. Treating \\ as an escaped backslash is common, but without specification, a minimal implementation handles \" only and treats other backslashes literally.
Field named timestamp: If a key-value pair uses timestamp as its key, it will overwrite the line's timestamp. A production system might prefix the line timestamp (__timestamp) or reject such lines.
Empty values: key= with nothing after should produce an empty string to match key="".
Implementation
def parse_log_stream(file_path):
"""
Generator that parses a log file line by line.
Yields a dict for each valid line containing 'timestamp'
and extracted key-value pairs.
"""
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
for line in f:
line = line.rstrip('\n\r')
# Skip blank lines
if not line.strip():
continue
parsed = parse_line(line)
if parsed:
yield parsed
def parse_line(line):
"""Parse a single log line into a dictionary."""
# Find where key-value pairs start (first '=')
first_eq = line.find('=')
if first_eq == -1:
return None # No key-value pairs, skip
# Extract timestamp: everything before the first key
# The key ends at '=', so we need to find where the key starts
# by scanning backward from '=' to find whitespace
timestamp_end = first_eq
while timestamp_end > 0 and line[timestamp_end - 1] not in ' \t':
timestamp_end -= 1
timestamp = line[:timestamp_end].strip()
if not timestamp:
return None
result = {'timestamp': timestamp}
# Parse key-value pairs starting from timestamp_end
i = timestamp_end
while i < len(line):
# Skip whitespace
while i < len(line) and line[i] in ' \t':
i += 1
if i >= len(line):
break
# Extract key
key_start = i
while i < len(line) and line[i] not in '= \t':
i += 1
if i >= len(line) or line[i] != '=':
break # Malformed, stop parsing this line
key = line[key_start:i]
i += 1 # Skip '='
# Extract value
if i >= len(line):
# Empty value at end of line
result[key] = ''
break
if line[i] == '"':
# Quoted value
i += 1 # Skip opening quote
value_chars = []
while i < len(line):
if line[i] == '\\' and i + 1 < len(line) and line[i + 1] == '"':
value_chars.append('"')
i += 2
elif line[i] == '"':
i += 1 # Skip closing quote
break
else:
value_chars.append(line[i])
i += 1
result[key] = ''.join(value_chars)
else:
# Unquoted value
value_start = i
while i < len(line) and line[i] not in ' \t':
i += 1
result[key] = line[value_start:i]
return result
Complexity
Time: O(n) per line, where n is the line length. Each character is examined once during tokenization.
Space: O(k) per line for the output dictionary, where k is the number of key-value pairs. The generator ensures total memory usage remains O(1) with respect to file size, since only one line is processed at a time.
Common Mistakes
-
Loading the entire file: Using
file.read()defeats the streaming requirement and causes memory issues with large files. -
Timestamp parsing fragility: Assuming the timestamp never contains spaces breaks on the second format. Scanning for the first
=and working backward is more robust. -
Incomplete escape handling: Forgetting that
\"inside quotes should become a literal"in the output. -
Whitespace handling: Not accounting for multiple consecutive spaces or tabs between key-value pairs.
-
Quoted values at line end: Failing to handle a quoted value that is the last token on the line (no trailing space).
Testing Strategy
Build test cases from the provided examples plus edge cases:
- Line with only a timestamp (no key-value pairs)
- Tabs as separators instead of spaces
- Trailing whitespace after the last value
- A quoted value at the end of the line with no space after
- Consecutive spaces inside a quoted value
- Empty quoted value as the last field
- A key named
timestampto verify behavior
A complete solution includes these test cases and validates that the generator yields correct dictionaries without loading the file into memory.