KatInterview

Generator-Based Parser for Structured Log Streams

StringsModel answer
MediumModel answerStringsparsinggeneratorsstring-processing

Last 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:

  1. ISO format without spaces: 2025-03-14T08:22:15Z
  2. 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-42 or count=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() or file.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.