KatInterview

Log Ingestion Engine with Prefix-Operator Query Filtering

StringsModel answer
EasyModel answerStringsparsingregexfiltering

Last 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>
FieldRules
timestampISO-8601 string, e.g. 2023-10-31T08:15:30Z. No whitespace.
levelOne of INFO, WARN, ERROR, DEBUG — always uppercase, always inside square brackets.
serviceAlphanumeric name, hyphens allowed, inside square brackets.
messageEverything 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 shapeWhat 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 tokenCase-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^4 log lines
  • Each line is at most 1000 characters
  • 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.