KatInterview

Upgrade a Streaming Log Filter to Multi-Code and JSON Output

Data Structure DesignModel answer
MediumModel answerData Structure Designpythonrefactoringstreaming

Last updated

Refactor a small Python log-counting script so it filters on several status codes, optionally writes JSON, streams multi-gigabyte files in constant memory, and stays unit-testable.

Scenario

Your team owns a small Python command-line utility called log-analyzer. At the moment it opens a local text file, walks through it one line at a time, checks whether the status code matches a single value, and prints how many lines matched.

Each log line is expected to look like this:

<timestamp> <status_code> <message...>

Existing code

def process_logs(file_path, target_code):
    count = 0
    with open(file_path, 'r') as f:
        for line in f:
            if str(target_code) in line.split()[1]:
                count += 1
    print(f"Total: {count}")

What you need to deliver

Rework the tool so that it:

  1. Accepts several status codes at once instead of one.
  2. Can optionally write its results to a JSON file rather than printing them to stdout.
  3. Copes with log files larger than 10 GB without reading the whole file into memory.
  4. Is organized so that it is maintainable and easy to unit-test.

Use this signature:

def process_logs(file_path, target_codes: list[int], output_path: str = None):
    ...

You may also split the work into helper functions or a class.

Constraints

  • Time: O(N), where N is the number of lines.
  • Extra space: O(K), where K is the number of target codes.
  • Handle gracefully: a missing file, blank lines, and malformed lines.
  • You can assume the file format is otherwise consistent.

What to cover in your answer

  • Any problems you notice in the existing code, not only the missing features.
  • Your design: how responsibilities are split and why.
  • The code itself, with its time and space complexity.
  • How you would test it without needing a giant file.

Hints

Hint 1

Read the current code skeptically: what does `str(target_code) in line.split()[1]` do when the target is 50 and the field is 503? What happens on a blank line?

Hint 2

Split the program into a pure parsing function, a pure counting function that accepts any iterable of lines, and a thin outer function that handles opening the file and choosing where output goes.

Hint 3

Iterating a file object is already lazy, so memory stays flat. Store the targets in a set for O(1) lookups and keep counts only for matched codes, which bounds memory by K.

Hint 4

Decide up front how each kind of line is treated (blank, malformed, valid but unmatched, matched) and how failures such as a missing file or an empty code list are reported.