Structured Log Parser with Prefix Filtering

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement a log ingestion and filtering component LogEngine that converts raw application log lines into LogRecord instances and answers multi-token search queries over those records.

Raw Line Specification

Every valid log entry is a single line formatted with single ASCII space delimiters between its four header sections:

<timestamp> [<level>] [<service>] <message>
  • <timestamp>: An ISO-8601 timestamp using ASCII digits in the form YYYY-MM-DDTHH:MM:SS, optionally followed by fractional seconds (.<digits>) and/or a timezone suffix (Z, +HH:MM, or -HH:MM), with no spaces.
  • <level>: One of the four uppercase severity labels INFO, WARN, ERROR, or DEBUG, enclosed in [ and ].
  • <service>: One or more ASCII letters, digits, or hyphens (A–Z, a–z, 0–9, -), enclosed in [ and ].
  • <message>: All remaining text on the line after the single space following [<service>], stored verbatim. The message must contain at least one non-whitespace character.
  • Optional user_id tag: Inspect whitespace-delimited words of <message> from left to right. If a standalone word begins with user_id= followed by one or more characters (user_id=<id>), record <id> in LogRecord.user_id (taking the first such word if several appear); otherwise leave user_id as None.

A trailing line break (\n or \r\n) at the end of a raw string is stripped prior to validation. Any line that fails this structure—such as missing brackets, lowercase severity, extra spaces before or between header fields, an empty/whitespace-only message, an embedded newline, or a non-string element—must be silently skipped while keeping valid records in their original order.

Search Filter Specification

LogEngine.search(records, query) splits query on whitespace into filter tokens and returns the matching LogRecord objects (preserving object identity and input order). A record matches when it satisfies every token in query (logical AND); an empty or whitespace-only query imposes zero constraints and returns all records.

Each token is evaluated according to its prefix:

  • level:<value>: Case-insensitive exact match against record.level.
  • service:<prefix>: Case-insensitive prefix match against record.service.
  • user:<id>: Case-sensitive exact match against record.user_id (never matches when user_id is None).
  • Any other token (including tokens with unrecognized prefixes before a colon): Case-insensitive prefix match against at least one whitespace-separated word in record.message.

Interface

from dataclasses import dataclass
from typing import List, Optional


@dataclass
class LogRecord:
    timestamp: str
    level: str
    service: str
    message: str
    user_id: Optional[str] = None


class LogEngine:
    def parse(self, raw_logs: List[str]) -> List[LogRecord]: ...
    def search(self, records: List[LogRecord], query: str) -> List[LogRecord]: ...

Examples

Example 1

raw_logs = [
    "2025-04-12T14:20:00Z [INFO] [order-api] Checkout completed user_id=acct_42",
    "2025-04-12T14:20:09Z [WARN] [order-worker] Inventory reservation delayed",
    "2025-04-12T14:20:15Z [ERROR] [billing-gateway] Charge timeout user_id=acct_99",
    "corrupted line missing brackets",
]

engine = LogEngine()
records = engine.parse(raw_logs)
# Keeps 3 LogRecord objects (drops the 4th line):
#   records[0].user_id == "acct_42"
#   records[1].user_id is None
#   records[2].user_id == "acct_99"

matches = engine.search(records, "level:error user:acct_99")
# Output: [records[2]]

Walk-through: parse discards the malformed fourth line and extracts user_id values where present. In search, level:error matches ERROR case-insensitively and user:acct_99 matches records[2].user_id case-sensitively, returning [records[2]].

Example 2

matches = engine.search(records, "service:order reserv")
# Output: [records[1]]

Walk-through: Both records[0] ("order-api") and records[1] ("order-worker") satisfy service:order, and among those two only records[1] contains a message word ("reservation") starting with "reserv".

Constraints

  • 0 <= len(raw_logs) <= 10^4
  • Each raw log string has length at most 1,000 characters.
  • 0 <= len(query) <= 200

Step-by-step walkthrough

  1. Understand the log layout and parsing contract

    We need to implement LogEngine with two methods: 1. parse(raw_logs): Convert each valid raw log string into a LogRecord dataclass while dropping any malformed line and preserving input order. 2. search(records, query): Return the original LogRecord objects (in input order) that satisfy every space-separated filter token in query.

    Here is how a valid raw log line breaks apart:

    2025-04-12T14:20:00Z [INFO] [order-api] Checkout completed user_id=acct_42
    |------------------| |----| |---------| |--------------------------------|
         timestamp       level    service                message
                                                          └─> user_id = "acct_42"
    

    To enforce the format strictly, we verify five rules on each line: - Single-space delimiters: Exactly one space separates <timestamp>, [<level>], [<service>], and <message>. A trailing newline (\n or \r\n) at the end of the line is stripped, whereas leading spaces or double spaces between header fields make the line malformed. - Timestamp: An ISO-8601 timestamp shape (YYYY-MM-DDTHH:MM:SS, optional fractional seconds like .123, and optional timezone Z or +HH:MM / -HH:MM), containing no spaces. - Level: Uppercase INFO, WARN, ERROR, or DEBUG inside square brackets. - Service: One or more ASCII letters, digits, or hyphens (A-Z, a-z, 0-9, -) inside square brackets. - Message: Everything after the single space following [<service>], stored verbatim, as long as it has at least one non-whitespace character.

  2. Match the exact log structure with a full-line regex

    We can validate all four sections in one step using a compiled regular expression (a pattern that specifies the exact characters allowed at each position).

    Using LINE_PATTERN.fullmatch(cleaned_line) gives us three safety guarantees at once: 1. fullmatch covers the whole string: Unlike re.search (which matches anywhere inside a string) or $ (which can still match right before a trailing newline), fullmatch rejects anything with extra prefix text or embedded newlines (\n is not matched by .). 2. Named capture groups ((?P<name>...)): Instead of brittle group numbers like match.group(1), we read match.group("timestamp"), match.group("level"), match.group("service"), and match.group("message") by name. 3. ASCII-only digits ([0-9]): In Python, \d on strings also matches non-ASCII Unicode digits such as "٣". Writing [0-9] accepts only standard ASCII digits.

    import re
    
    # Match the entire raw log line: "<timestamp> [<level>] [<service>] <message>".
    # Use [0-9] instead of \d because Python's \d also accepts non-ASCII Unicode digits like "٣".
    LINE_PATTERN = re.compile(
        r"(?P<timestamp>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
        r"(?:\.[0-9]+)?(?:Z|[+-][0-9]{2}:[0-9]{2})?)"
        r" \[(?P<level>INFO|WARN|ERROR|DEBUG)\]"
        r" \[(?P<service>[A-Za-z0-9-]+)\]"
        r" (?P<message>.*)"
    )
    
  3. Extract the optional `user_id` from message words

    Inside <message>, we look for a standalone whitespace-delimited token formatted as user_id=<value>. If one exists with a non-empty <value>, we extract that value; otherwise user_id is None.

    Why loop over message.split() instead of a regex with \b (a regex word boundary)? Because \b also triggers right after punctuation! On "foo.user_id=9", \b matches between . and u, falsely extracting "9". Splitting on whitespace checks whole words directly, so "xuser_id=9" and "user_id=" (empty value) are cleanly ignored, and if two user_id=... tokens appear, the first one wins.

    from typing import Optional
    
    USER_PREFIX = "user_id="
    
    
    def extract_user_id(message: str) -> Optional[str]:
        """Return the value of the first standalone word formatted as user_id=<value>, or None."""
        # Splitting on whitespace ensures "xuser_id=9" or "foo.user_id=9" is not mistaken
        # for a standalone user_id=<value> token.
        for word in message.split():
            if word.startswith(USER_PREFIX) and len(word) > len(USER_PREFIX):
                return word[len(USER_PREFIX):]
        return None
    
  4. Parse a batch of raw lines safely

    Now we write parse_line(line) to turn one raw string into either a LogRecord or None. Checking isinstance(line, str) first ensures a stray None in a messy input list drops cleanly rather than raising an AttributeError. After fullmatch succeeds, we also check message.strip() == "" so lines like "2025-04-12T14:20:00Z [INFO] [svc] " (blank message) are rejected.

    Then LogEngine.parse loops through raw_logs and collects every non-None record in order.

    from typing import List, Optional
    
    
    def parse_line(line: str) -> Optional[LogRecord]:
        """Parse one raw log string into a LogRecord, or return None if malformed."""
        if not isinstance(line, str):
            return None
    
        # Strip only a trailing line ending (\n or \r\n); leading spaces or double spaces
        # between header fields must fail fullmatch and drop the line.
        cleaned_line = line.rstrip("\r\n")
        match = LINE_PATTERN.fullmatch(cleaned_line)
        if match is None:
            return None
    
        # Keep the message text verbatim, but reject messages that are empty or all spaces.
        message = match.group("message")
        if message.strip() == "":
            return None
    
        return LogRecord(
            timestamp=match.group("timestamp"),
            level=match.group("level"),
            service=match.group("service"),
            message=message,
            user_id=extract_user_id(message),
        )
    
  5. Understand the four search token rules

    In search(records, query), calling query.split() (with no arguments) splits on any run of spaces and returns [] for "" or " ". Because a record must satisfy all tokens in the list (logical AND), 0 tokens means zero restrictions—every record matches.

    Each token falls into one of four cases:

    Token            Field       Match type & case sensitivity   Matches?
    ---------------  ----------  ------------------------------  ----------------------------------------------
    level:error      level       exact, case-insensitive         "ERROR" -> Yes, "WARN" -> No
    service:ORDER    service     prefix, case-insensitive        "order-api" -> Yes, "my-order" -> No
    user:acct_42     user_id     exact, case-sensitive           "acct_42" -> Yes, "ACCT_42" -> No
    reserv           message     word prefix, case-insensitive   "Inventory reservation" -> Yes ("reservation"),
                                                                 "unreserved" -> No ("reserv" is not at start)
    

    Notice what happens when a token contains a colon that is not one of the three known operators (such as "inv:7" or "slot=inv:7"): it falls straight into the fourth rule and is matched as a case-insensitive prefix against whitespace-separated words in message.

  6. Filter records with short-circuit AND matching

    For each record, we test the query tokens one by one and return False as soon as any token fails (short-circuit evaluation).

    Notice a helpful optimization: splitting and lower-casing a 1,000-character message allocates a new string and list of words. If a query is "level:ERROR timeout" and 95% of our logs are INFO, checking level:ERROR rejects those INFO records immediately—we never need to split their messages at all! By keeping message_words = None until we actually reach a free-text token, we split record.message at most once per record, and never when field filters already rejected it or when query has no free-text tokens.

    from typing import List, Optional
    
    
    def has_word_prefix(message_words: List[str], prefix: str) -> bool:
        """True when at least one lower-cased message word starts with prefix."""
        for word in message_words:
            if word.startswith(prefix):
                return True
        return False
    
    
    def record_matches(record: LogRecord, tokens: List[str]) -> bool:
        """True when record satisfies every query token (logical AND)."""
        # Lazily split and lowercase the message at most once per record, and only if the
        # record passes earlier field filters and the query actually has a free-text token.
        message_words: Optional[List[str]] = None
    
        for token in tokens:
            if token.startswith("level:"):
                expected_level = token[len("level:"):].lower()
                if record.level.lower() != expected_level:
                    return False
            elif token.startswith("service:"):
                service_prefix = token[len("service:"):].lower()
                if not record.service.lower().startswith(service_prefix):
                    return False
            elif token.startswith("user:"):
                # user_id matching is exact and case-sensitive ("acct_42" != "ACCT_42").
                expected_user = token[len("user:"):]
                if record.user_id != expected_user:
                    return False
            else:
                if message_words is None:
                    message_words = record.message.lower().split()
                if not has_word_prefix(message_words, token.lower()):
                    return False
    
        return True
    
  7. Trace the examples and assemble the complete solution

    Let's walk through both statement examples step by step:

    Input raw_logs:
      [0] "2025-04-12T14:20:00Z [INFO] [order-api] Checkout completed user_id=acct_42"
          -> LogRecord(timestamp="2025-04-12T14:20:00Z", level="INFO",
                       service="order-api", message="Checkout completed user_id=acct_42",
                       user_id="acct_42")
      [1] "2025-04-12T14:20:09Z [WARN] [order-worker] Inventory reservation delayed"
          -> LogRecord(timestamp="2025-04-12T14:20:09Z", level="WARN",
                       service="order-worker", message="Inventory reservation delayed",
                       user_id=None)
      [2] "2025-04-12T14:20:15Z [ERROR] [billing-gateway] Charge timeout user_id=acct_99"
          -> LogRecord(timestamp="2025-04-12T14:20:15Z", level="ERROR",
                       service="billing-gateway", message="Charge timeout user_id=acct_99",
                       user_id="acct_99")
      [3] "corrupted line missing brackets"
          -> fullmatch is None -> dropped
    
    Query 1: "level:error user:acct_99"  -> tokens = ["level:error", "user:acct_99"]
      records[0]: level "info" != "error" -> stops immediately (False)
      records[1]: level "warn" != "error" -> stops immediately (False)
      records[2]: level "error" == "error" AND user_id "acct_99" == "acct_99" -> True
      Result: [records[2]]
    
    Query 2: "service:order reserv"      -> tokens = ["service:order", "reserv"]
      records[0]: "order-api".startswith("order") is True;
                  words ["checkout", "completed", "user_id=acct_42"] -> none starts with "reserv" (False)
      records[1]: "order-worker".startswith("order") is True;
                  words ["inventory", "reservation", "delayed"] -> "reservation".startswith("reserv") (True)
      records[2]: "billing-gateway".startswith("order") is False -> stops immediately
      Result: [records[1]]
    

    Here is the complete solution:

    from typing import List, Optional
    from dataclasses import dataclass
    import re
    
    
    @dataclass
    class LogRecord:
        timestamp: str
        level: str
        service: str
        message: str
        user_id: Optional[str] = None
    
    
    # Match the entire raw log line: "<timestamp> [<level>] [<service>] <message>".
    # Use [0-9] instead of \d because Python's \d also accepts non-ASCII Unicode digits like "٣".
    LINE_PATTERN = re.compile(
        r"(?P<timestamp>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
        r"(?:\.[0-9]+)?(?:Z|[+-][0-9]{2}:[0-9]{2})?)"
        r" \[(?P<level>INFO|WARN|ERROR|DEBUG)\]"
        r" \[(?P<service>[A-Za-z0-9-]+)\]"
        r" (?P<message>.*)"
    )
    USER_PREFIX = "user_id="
    
    
    def extract_user_id(message: str) -> Optional[str]:
        """Return the value of the first standalone word formatted as user_id=<value>, or None."""
        # Splitting on whitespace ensures "xuser_id=9" or "foo.user_id=9" is not mistaken
        # for a standalone user_id=<value> token.
        for word in message.split():
            if word.startswith(USER_PREFIX) and len(word) > len(USER_PREFIX):
                return word[len(USER_PREFIX):]
        return None
    
    
    def parse_line(line: str) -> Optional[LogRecord]:
        """Parse one raw log string into a LogRecord, or return None if malformed."""
        if not isinstance(line, str):
            return None
    
        # Strip only a trailing line ending (\n or \r\n); leading spaces or double spaces
        # between header fields must fail fullmatch and drop the line.
        cleaned_line = line.rstrip("\r\n")
        match = LINE_PATTERN.fullmatch(cleaned_line)
        if match is None:
            return None
    
        # Keep the message text verbatim, but reject messages that are empty or all spaces.
        message = match.group("message")
        if message.strip() == "":
            return None
    
        return LogRecord(
            timestamp=match.group("timestamp"),
            level=match.group("level"),
            service=match.group("service"),
            message=message,
            user_id=extract_user_id(message),
        )
    
    
    def has_word_prefix(message_words: List[str], prefix: str) -> bool:
        """True when at least one lower-cased message word starts with prefix."""
        for word in message_words:
            if word.startswith(prefix):
                return True
        return False
    
    
    def record_matches(record: LogRecord, tokens: List[str]) -> bool:
        """True when record satisfies every query token (logical AND)."""
        # Lazily split and lowercase the message at most once per record, and only if the
        # record passes earlier field filters and the query actually has a free-text token.
        message_words: Optional[List[str]] = None
    
        for token in tokens:
            if token.startswith("level:"):
                expected_level = token[len("level:"):].lower()
                if record.level.lower() != expected_level:
                    return False
            elif token.startswith("service:"):
                service_prefix = token[len("service:"):].lower()
                if not record.service.lower().startswith(service_prefix):
                    return False
            elif token.startswith("user:"):
                # user_id matching is exact and case-sensitive ("acct_42" != "ACCT_42").
                expected_user = token[len("user:"):]
                if record.user_id != expected_user:
                    return False
            else:
                if message_words is None:
                    message_words = record.message.lower().split()
                if not has_word_prefix(message_words, token.lower()):
                    return False
    
        return True
    
    
    class LogEngine:
        def parse(self, raw_logs: List[str]) -> List[LogRecord]:
            # Keep valid records in their original order and silently drop malformed lines.
            records: List[LogRecord] = []
            for line in raw_logs:
                record = parse_line(line)
                if record is not None:
                    records.append(record)
            return records
    
        def search(self, records: List[LogRecord], query: str) -> List[LogRecord]:
            # query.split() collapses arbitrary whitespace; an empty/blank query gives []
            # so every record matches and is returned in input order.
            tokens = query.split()
            matches: List[LogRecord] = []
            for record in records:
                if record_matches(record, tokens):
                    matches.append(record)
            return matches
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of LogEngine as a two-desk mailroom. At the intake desk (parse), every raw log string is held up against a rigid stencil (<timestamp> [<level>] [<service>] <message>): if a line matches the stencil, we copy its fields onto a clean LogRecord card and pull out any user_id=<value> tag from the message; if anything is missing or out of place, we toss the line out. At the search desk (search), a query string like "service:order reserv" becomes a short checklist of requirements, and we hand back every card that passes all items on the checklist.

A naive parser that splits on spaces with line.split() breaks apart messages or collapses intentional multiple spaces inside the message text, while a naive search that checks "reserv" in record.message.lower() wrongly matches mid-word substrings like "unreserved" instead of word prefixes. Even regexes need care: re.search allows garbage before the timestamp, and \buser_id= matches right after punctuation like "foo.user_id=9".

Here is how our solution processes a 4-line batch and queries "service:order reserv": - Line 1 ("2025-04-12T14:20:00Z [INFO] [order-api] Checkout completed user_id=acct_42") passes fullmatch—checking the entire line from first character to last—and extracts user_id="acct_42". - Line 2 ("2025-04-12T14:20:09Z [WARN] [order-worker] Inventory reservation delayed") passes fullmatch with user_id=None, Line 3 ("... [billing-gateway] Charge timeout user_id=acct_99") extracts "acct_99", and Line 4 ("corrupted line missing brackets") fails fullmatch and is dropped. - On "service:order reserv", records[0] passes "order-api".startswith("order") yet none of its words start with "reserv", records[1] passes both "order-worker".startswith("order") and "reservation".startswith("reserv"), and records[2] fails "billing-gateway".startswith("order") immediately without even splitting its message.

Complexity

Let N be the number of log lines (or parsed records), M be the maximum character length of a line (<= 1,000), W be the maximum number of words in a message, and T be the number of tokens in query.

  • parse: O(N * M) time (linear in total input characters) and O(N * M) space to store the resulting LogRecord objects. Our regular expression (a character-by-character pattern matcher) is anchored at the start and has no overlapping repetitions, so fullmatch scans each line once from left to right, and extract_user_id scans the message characters once more to split words.
  • search: O(N * (M + T * M)) worst-case character comparisons, and O(N) when query is empty. For each record, operator tokens (level:, service:, user:) compare short header strings directly, and short-circuit evaluation (stopping at the first False token) skips the rest of the tokens—and skips splitting record.message altogether—whenever an earlier filter fails. When a free-text token is reached, we lower-case and split record.message once in O(M) time and test up to W words with startswith. With N <= 10^4 and M <= 1,000, a full scan touches at most ~10 million characters and finishes in milliseconds.
  • Auxiliary space in search: O(M + T) for the query token list and one record's temporary message_words list, plus O(matches) references in the returned list.

Edge cases

  • Empty logs or empty / whitespace-only query: parse([]) returns []; search(records, "") and search(records, " ") produce zero tokens and return all records in input order.
  • File line endings vs embedded newlines: A trailing \n or \r\n is stripped so lines read from log files parse cleanly, whereas an embedded \n in the middle of a message fails fullmatch because . does not match newlines.
  • Missing or whitespace-only message: "2025-04-12T14:20:00Z [INFO] [svc]" and "... [svc] " are both dropped because a log entry must carry a non-blank message.
  • Tricky user_id tokens: "user_id=" (empty value) and "xuser_id=9" (prefix attached) both yield user_id=None. If a message contains two valid user_id=<value> words, the first one wins.
  • Case sensitivity differences: level:, service:, and free-text word prefixes are case-insensitive (level:error matches ERROR), whereas user: is exact and case-sensitive (user:ACCT_42 does not match acct_42).
  • Colons that are not known operators: Tokens such as "inv:7" or "slot=inv:7" do not start with level:, service:, or user:, so they are treated as free-text word prefixes against message.

Common mistakes

  • Splitting the raw line with line.split(): Calling split() without a limit breaks the message into pieces and collapses multiple spaces inside the message into single spaces, altering the original message text.
  • Using re.search or re.match instead of re.fullmatch: re.search accepts garbage before the timestamp, and re.match with $ still matches right before a trailing newline.
  • Using \d instead of [0-9]: In Python 3, \d on str patterns matches non-ASCII Unicode digits like "٣", accepting malformed timestamps unless [0-9] or re.ASCII is used.
  • Substring checks instead of prefix checks: Writing prefix in record.service.lower() lets service:api falsely match order-api, and writing prefix in record.message.lower() lets "eckout" falsely match "checkout". Always check startswith on the service name and on each individual message word.
  • Splitting the query with query.split(" "): Multiple spaces in "level:ERROR timeout" produce an empty string token "" when passing " " explicitly; query.split() with no arguments ignores extra spaces cleanly.

Follow-up questions

  • What indexing structures would you introduce if the log volume scaled to tens of millions of entries and searches still needed to finish in well under a second? Build an inverted index (a lookup table mapping each unique lower-cased word to a posting list, a sorted list of record IDs containing that word) alongside a sorted vocabulary list or trie (a prefix tree where each path of characters from the root spells a shared prefix) so word-prefix queries scan only matching dictionary terms and union their posting lists. For structured fields, keep four bitmaps (compact bit arrays with one bit per record ID) for the four level values, a hash map from user_id to posting lists, and a small prefix table over distinct service names. Answering an AND query then intersects the posting lists starting from the rarest filter rather than scanning tens of millions of records, and partitioning indexes into time shards (such as one shard per hour or day) lets workers search shards in parallel.
  • How would you redesign query parsing to handle boolean OR, NOT, parentheses, and time-window filters? Replace the flat token list with a recursive descent parser (a set of small functions, one per operator precedence level) that builds a boolean expression tree where NOT binds tightest, implicit AND sits in the middle, and OR binds loosest, with parentheses overriding precedence. Each tree node exposes matches(record)—or returns a posting-list set when backed by an index—with our existing single-token check at the leaves. For time-window range filters, normalize every timestamp to a UTC epoch number at parse time rather than comparing raw strings, because "2025-04-12T09:00:00+05:30" (03:30Z) is earlier in real time than "2025-04-12T08:00:00Z" even though "09" sorts after "08" alphabetically.
  • How would you structure the ingestion architecture when upstream services emit heterogeneous formats rather than a single bracketed text layout? Route raw logs through a durable message queue (such as Kafka) into stateless parser workers that select a format-specific adapter (JsonLogParser, LogfmtParser, BracketedTextParser) using explicit source metadata (service tag or collector config) rather than brittle content guessing. Every adapter normalizes its input into one canonical schema—UTC timestamp, standard severity level, service name, message, user_id, and an attributes dictionary for extra fields—so downstream indexing and search stay completely format-agnostic. Instead of silently dropping malformed lines in production, route failed lines to a dead-letter queue (a side storage stream holding rejected messages and failure reasons) and alert when any service's parse-error rate spikes after a deploy.

Follow-up questions

Similar questions

More Kikoff interview questions

All 4 Kikoff questions →