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 formYYYY-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 labelsINFO,WARN,ERROR, orDEBUG, 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_idtag: Inspect whitespace-delimited words of<message>from left to right. If a standalone word begins withuser_id=followed by one or more characters (user_id=<id>), record<id>inLogRecord.user_id(taking the first such word if several appear); otherwise leaveuser_idasNone.
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 againstrecord.level.service:<prefix>: Case-insensitive prefix match againstrecord.service.user:<id>: Case-sensitive exact match againstrecord.user_id(never matches whenuser_idisNone).- 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,000characters. 0 <= len(query) <= 200
Step-by-step walkthrough
Understand the log layout and parsing contract
We need to implement
LogEnginewith two methods: 1.parse(raw_logs): Convert each valid raw log string into aLogRecorddataclass while dropping any malformed line and preserving input order. 2.search(records, query): Return the originalLogRecordobjects (in input order) that satisfy every space-separated filter token inquery.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 (\nor\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 timezoneZor+HH:MM/-HH:MM), containing no spaces. - Level: UppercaseINFO,WARN,ERROR, orDEBUGinside 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.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.fullmatchcovers the whole string: Unlikere.search(which matches anywhere inside a string) or$(which can still match right before a trailing newline),fullmatchrejects anything with extra prefix text or embedded newlines (\nis not matched by.). 2. Named capture groups ((?P<name>...)): Instead of brittle group numbers likematch.group(1), we readmatch.group("timestamp"),match.group("level"),match.group("service"), andmatch.group("message")by name. 3. ASCII-only digits ([0-9]): In Python,\don 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>.*)" )Extract the optional `user_id` from message words
Inside
<message>, we look for a standalone whitespace-delimited token formatted asuser_id=<value>. If one exists with a non-empty<value>, we extract that value; otherwiseuser_idisNone.Why loop over
message.split()instead of a regex with\b(a regex word boundary)? Because\balso triggers right after punctuation! On"foo.user_id=9",\bmatches between.andu, falsely extracting"9". Splitting on whitespace checks whole words directly, so"xuser_id=9"and"user_id="(empty value) are cleanly ignored, and if twouser_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 NoneParse a batch of raw lines safely
Now we write
parse_line(line)to turn one raw string into either aLogRecordorNone. Checkingisinstance(line, str)first ensures a strayNonein a messy input list drops cleanly rather than raising anAttributeError. Afterfullmatchsucceeds, we also checkmessage.strip() == ""so lines like"2025-04-12T14:20:00Z [INFO] [svc] "(blank message) are rejected.Then
LogEngine.parseloops throughraw_logsand collects every non-Nonerecord 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), )Understand the four search token rules
In
search(records, query), callingquery.split()(with no arguments) splits on any run of spaces and returns[]for""or" ". Because a record must satisfy all tokens in the list (logicalAND),0tokens 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 inmessage.Filter records with short-circuit AND matching
For each record, we test the query tokens one by one and return
Falseas soon as any token fails (short-circuit evaluation).Notice a helpful optimization: splitting and lower-casing a 1,000-character
messageallocates a new string and list of words. If a query is"level:ERROR timeout"and 95% of our logs areINFO, checkinglevel:ERRORrejects thoseINFOrecords immediately—we never need to split their messages at all! By keepingmessage_words = Noneuntil we actually reach a free-text token, we splitrecord.messageat most once per record, and never when field filters already rejected it or whenqueryhas 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 TrueTrace 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 resultingLogRecordobjects. Our regular expression (a character-by-character pattern matcher) is anchored at the start and has no overlapping repetitions, sofullmatchscans each line once from left to right, andextract_user_idscans the message characters once more to split words.search: O(N * (M + T * M)) worst-case character comparisons, and O(N) whenqueryis empty. For each record, operator tokens (level:,service:,user:) compare short header strings directly, and short-circuit evaluation (stopping at the firstFalsetoken) skips the rest of the tokens—and skips splittingrecord.messagealtogether—whenever an earlier filter fails. When a free-text token is reached, we lower-case and splitrecord.messageonce in O(M) time and test up toWwords withstartswith. WithN <= 10^4andM <= 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 temporarymessage_wordslist, plus O(matches) references in the returned list.
Edge cases
- Empty logs or empty / whitespace-only query:
parse([])returns[];search(records, "")andsearch(records, " ")produce zero tokens and return all records in input order. - File line endings vs embedded newlines: A trailing
\nor\r\nis stripped so lines read from log files parse cleanly, whereas an embedded\nin the middle of a message failsfullmatchbecause.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_idtokens:"user_id="(empty value) and"xuser_id=9"(prefix attached) both yielduser_id=None. If a message contains two validuser_id=<value>words, the first one wins. - Case sensitivity differences:
level:,service:, and free-text word prefixes are case-insensitive (level:errormatchesERROR), whereasuser:is exact and case-sensitive (user:ACCT_42does not matchacct_42). - Colons that are not known operators: Tokens such as
"inv:7"or"slot=inv:7"do not start withlevel:,service:, oruser:, so they are treated as free-text word prefixes againstmessage.
Common mistakes
- Splitting the raw line with
line.split(): Callingsplit()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.searchorre.matchinstead ofre.fullmatch:re.searchaccepts garbage before the timestamp, andre.matchwith$still matches right before a trailing newline. - Using
\dinstead of[0-9]: In Python 3,\donstrpatterns matches non-ASCII Unicode digits like"٣", accepting malformed timestamps unless[0-9]orre.ASCIIis used. - Substring checks instead of prefix checks: Writing
prefix in record.service.lower()letsservice:apifalsely matchorder-api, and writingprefix in record.message.lower()lets"eckout"falsely match"checkout". Always checkstartswithon 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
levelvalues, a hash map fromuser_idto posting lists, and a small prefix table over distinctservicenames. Answering anANDquery 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 whereNOTbinds tightest, implicitANDsits in the middle, andORbinds loosest, with parentheses overriding precedence. Each tree node exposesmatches(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 anattributesdictionary 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
- 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?
- How would you redesign query parsing to handle boolean `OR`, `NOT`, parentheses, and time-window filters?
- How would you structure the ingestion architecture when upstream services emit heterogeneous formats rather than a single bracketed text layout?
Similar questions
- Screen External Identity Verification Payloads
- Real-Time Credit Risk Scoring Architecture
- Format Transaction Rows as Receipt Blocks
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination