Log Ingestion Engine with Prefix-Operator Query Filtering
StringsModel answerLast updated
Build a two-phase pipeline that parses raw server log lines into structured records and filters them using a mini query language of typed prefix tokens.
Background
High-traffic backend systems produce a continuous stream of log lines from multiple services. Before any alerting, monitoring, or debugging tool can use those logs, two things need to happen: the raw text has to be turned into structured data, and there has to be a way to narrow that data down to the entries you actually care about.
Your job is to build a small log engine that handles both steps.
Part 1 — Parsing
Write a parse method that takes a list of raw log strings and returns a list of LogRecord objects. Lines that do not conform to the expected format must be silently discarded.
Expected line format
<timestamp> [<level>] [<service>] <message>
| Field | Rules |
|---|---|
timestamp | ISO-8601 string, e.g. 2023-10-31T08:15:30Z. No whitespace. |
level | One of INFO, WARN, ERROR, DEBUG — always uppercase, always inside square brackets. |
service | Alphanumeric name, hyphens allowed, inside square brackets. |
message | Everything that follows. If the message contains a token of the form user_id=<value>, extract <value> into the user_id field. Otherwise user_id is None. |
A line is malformed if any field is missing, the brackets are wrong, the level is not one of the four allowed values, or the structure deviates in any other way.
Part 2 — Searching
Write a search method that accepts a list of LogRecord objects and a query string, and returns only the records that satisfy every token in the query (logical AND). An empty query returns all records.
Query token types
| Token shape | What it matches |
|---|---|
level:<value> | Exact match on level, case-insensitive |
service:<value> | Prefix match on service, case-insensitive |
user:<value> | Exact match on user_id, case-sensitive; None never matches |
| Any other token | Case-insensitive prefix match against any whitespace-delimited word in 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]:
"""Return structured records; drop malformed lines."""
pass
def search(self, records: List[LogRecord], query: str) -> List[LogRecord]:
"""Return records satisfying every token in query."""
pass
Examples
Example 1 — Basic parse and search
logs = [
"2023-10-31T08:15:30Z [INFO] [auth-svc] User login success user_id=u_101",
"2023-10-31T08:15:35Z [ERROR] [payment-svc] Card decline user_id=u_202",
"this line is not valid and should be dropped",
]
engine = LogEngine()
records = engine.parse(logs)
# len(records) == 2
# records[0].user_id == 'u_101'
# records[1].user_id == 'u_202'
engine.search(records, "level:ERROR user:u_202")
# → [records[1]]
Example 2 — Service prefix and free-text word prefix
engine.search(records, "service:auth log")
# → [records[0]]
# 'auth' is a prefix of 'auth-svc'; 'log' is a prefix of 'login'
Constraints
0 <= N <= 10^4log lines- Each line is at most
1000characters 0 <= len(query) <= 200- An empty or whitespace-only query returns all records unchanged
Hints
Hint 1
Use a single anchored regex with `fullmatch` to validate and capture all four fields at once. Splitting on whitespace is tempting but will silently accept lines that are structurally wrong.
Hint 2
For `user_id`, search the message with a lookbehind that ensures the key starts on a word boundary, so something like `xuser_id=5` is not captured.
Hint 3
Turn the query into a list of predicate functions compiled once before looping over records. `all(p(r) for p in predicates)` then expresses the AND logic directly, and an empty predicate list makes the empty-query case fall out for free.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits cleanly into two independent pieces. Get parsing right first — the search logic is short and mechanical once the data is clean.
Parsing
The core risk in parsing is being too lenient. A split(maxsplit=3) approach will accept lines like ts [INFO]auth msg (missing space before the service bracket) because split does not care about structure — it just finds whitespace. A single anchored fullmatch against a regex that encodes the exact format fixes this: if the line does not match the whole pattern, it is dropped.
The regex has four capture groups:
(\d{4}-\d{2}-\d{2}T\S+) \[(INFO|WARN|ERROR|DEBUG)\] \[([A-Za-z0-9-]+)\] (\S.*)
- Timestamp: a date, a literal
T, then non-whitespace — strict enough to reject obvious garbage without requiring a full ISO-8601 parser. - Level: a closed alternation. This is case-sensitive by design;
[info]is malformed per the spec. - Service: alphanumerics and hyphens only, no underscores or spaces.
- Message: starts with
\S(not whitespace), then anything. This rejects a line that ends after the service bracket.
For user_id, search the captured message with (?<!\S)user_id=(\S+). The negative lookbehind (?<!\S) ensures the u is either at the start of the string or preceded by whitespace, so xuser_id=5 and bad-user_id=5 do not match. Take the first occurrence and store the captured value; if there is no match, leave user_id as None.
Strip \r\n from each line before matching to handle files read on Windows.
Searching
Compile the query once into a list of predicates, then evaluate each record against all of them with all(). This approach has three benefits: behavior is independent of record order, all() short-circuits on the first failing predicate, and the empty-query case needs no special handling (all([]) is True).
Predicate compilation per token:
| Token | Predicate |
|---|---|
level:X | r.level.lower() == x.lower() |
service:X | r.service.lower().startswith(x.lower()) |
user:X | r.user_id == x (exact, case-sensitive; None never equals a string) |
| anything else | any(w.startswith(token.lower()) for w in r.message.lower().split()) |
One subtlety: a token like http://example.com contains a colon. The spec says only tokens without a colon prefix are free text, but the recognized operators are level, service, and user. A token whose prefix is something else should be treated as free text rather than silently dropped — otherwise the user gets back more results than expected with no error. Falling through to the free-text predicate is the right call.
Complexity
- Parse: O(L) total, where L is the sum of all line lengths. Regex matching is linear because there are no nested quantifiers that can backtrack. Space is O(N) for the returned records.
- Search: O(Q) to compile the query. Per-record evaluation is O(Q + W) where W is the message length, giving O(N · (Q + W)) overall. With N ≤ 10⁴ and lines ≤ 1000 chars this is comfortably under 10⁷ operations.
Edge cases worth mentioning
user:u_1never matches a record whereuser_idisNone.level:with an empty value matches nothing (no level equals the empty string).service:with an empty value matches everything, because every string starts with""— this falls naturally fromstr.startswith("").- Duplicate or contradictory tokens like
level:ERROR level:INFOare ANDed, so the result is empty. user_id=u_1is itself a whitespace-delimited word in the message, so the free-text tokenuserwill match it. This is consistent with the spec and worth noting out loud.- Free-text prefix matching is case-insensitive, so
LOGmatcheslogin.
Complete solution
import re
from dataclasses import dataclass
from typing import Callable, List, Optional
# Compile once at module level — not per call.
_LOG_RE = re.compile(
r'(\d{4}-\d{2}-\d{2}T\S+) '
r'\[(INFO|WARN|ERROR|DEBUG)\] '
r'\[([A-Za-z0-9-]+)\] '
r'(\S.*)'
)
_USER_RE = re.compile(r'(?<!\S)user_id=(\S+)')
Predicate = Callable[["LogRecord"], bool]
@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]:
records: List[LogRecord] = []
for line in raw_logs or []:
if not isinstance(line, str):
continue
m = _LOG_RE.fullmatch(line.rstrip("\r\n"))
if not m:
continue
timestamp, level, service, message = m.groups()
uid_match = _USER_RE.search(message)
records.append(LogRecord(
timestamp=timestamp,
level=level,
service=service,
message=message,
user_id=uid_match.group(1) if uid_match else None,
))
return records
def search(self, records: List[LogRecord], query: str) -> List[LogRecord]:
predicates = [self._compile(tok) for tok in (query or "").split()]
return [r for r in records if all(p(r) for p in predicates)]
@staticmethod
def _compile(token: str) -> Predicate:
key, sep, value = token.partition(":")
if sep:
k = key.lower()
if k == "level":
v = value.lower()
return lambda r, v=v: r.level.lower() == v
if k == "service":
v = value.lower()
return lambda r, v=v: r.service.lower().startswith(v)
if k == "user":
# Case-sensitive exact match; capture value in default arg.
return lambda r, v=value: r.user_id == v
# Fall through: free-text word-prefix match.
t = token.lower()
return lambda r, t=t: any(w.startswith(t) for w in r.message.lower().split())
Note the v=v and t=t default-argument captures in the lambdas. Without them, every lambda closes over the same variable and they all use the last value assigned — a classic Python closure bug that is easy to miss in a screen.
Common mistakes
- Using
split(maxsplit=3)instead of a structured regex — too permissive. - Forgetting
fullmatchand usingsearchormatch— allows garbage before or after the pattern. - Matching
user_idwithout a word-boundary guard —xuser_id=5gets extracted. - Writing special-case code for an empty query instead of letting
all([])handle it. - Lambda closure bug — not binding loop variables into default arguments.
Scale follow-up
If the record count grows to tens of millions, sequential scanning becomes too slow. The fix is to build indexes at ingest time: a hash map from level to posting list, a trie or sorted term dictionary for service-prefix lookups, a hash map from user_id to posting list, and an inverted index over message words for free-text prefix queries. Query evaluation then becomes a series of set intersections on posting lists rather than a full scan.