Upgrade a Streaming Log Filter to Multi-Code and JSON Output
Data Structure DesignModel answerLast 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:
- Accepts several status codes at once instead of one.
- Can optionally write its results to a JSON file rather than printing them to stdout.
- Copes with log files larger than 10 GB without reading the whole file into memory.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
This is really a small refactoring exercise. A strong answer first audits the existing code, then restructures it so the new features fall out naturally.
Problems in the existing code
- Substring matching is incorrect.
str(target_code) in line.split()[1]tests for a substring, so a target of50also matches500and503. The status must be parsed to an integer and compared for equality. - It crashes on bad input. A blank line or a line with a single token raises
IndexError. A non-numeric status field is not handled either. - Needless tokenizing.
split()breaks up the whole message when only the first two fields matter.split(maxsplit=2)stops early. - It is hard to test. Opening the file, counting, and printing all happen in one function, so a test would need a real file and captured stdout.
Design
Use three layers:
- Parse: a pure function that takes one line and returns the integer status, or
Noneif the line is malformed. - Count: a pure function that takes any iterable of lines and a set of target codes, and returns a result dictionary.
- I/O boundary:
process_logsopens the file, feeds it to the counter, and sends the result to a single output routine that writes either to stdout or to a JSON file.
Iterating over a file object reads in buffered chunks and yields one line at a time, so memory use is constant regardless of file size. A set gives O(1) membership checks, and a Counter that only records matched targets never holds more than K entries.
Line-handling rules
Every line falls into exactly one category:
- Blank or whitespace-only: ignored, not counted as malformed.
- Malformed (fewer than two fields, or a non-integer status): counted in
malformed_linesand skipped. - Valid but not targeted: ignored.
- Valid and targeted: added to that code's count.
Because each line has one status and the targets are deduplicated by the set, nothing is double counted, and total always equals the sum of the per-code counts.
Code
import argparse
import json
import os
import sys
import tempfile
from collections import Counter
from typing import Iterable, Optional, TextIO
def parse_status(line: str) -> Optional[int]:
"""Return the status from 'timestamp status message', or None if malformed."""
parts = line.split(maxsplit=2)
if len(parts) < 2:
return None
try:
return int(parts[1])
except ValueError:
return None
def count_matching(lines: Iterable[str], targets: set) -> dict:
"""Pure logic: works on a file, a list, or io.StringIO."""
per_code = Counter()
malformed = 0
for line in lines:
if not line or line.isspace():
continue
code = parse_status(line)
if code is None:
malformed += 1
elif code in targets:
per_code[code] += 1
return {
"total": sum(per_code.values()),
"by_code": {str(c): per_code[c] for c in sorted(targets)},
"malformed_lines": malformed,
}
def _write_json_atomic(result: dict, output_path: str) -> None:
directory = os.path.dirname(os.path.abspath(output_path))
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as tmp:
json.dump(result, tmp, indent=2)
os.replace(tmp_path, output_path)
except BaseException:
if os.path.exists(tmp_path):
os.remove(tmp_path)
raise
def emit(result: dict, output_path: Optional[str] = None,
stream: TextIO = sys.stdout) -> None:
if output_path is None:
print(f"Total: {result['total']}", file=stream)
for code, n in result["by_code"].items():
print(f" {code}: {n}", file=stream)
if result["malformed_lines"]:
print(f"Skipped malformed lines: {result['malformed_lines']}", file=stream)
else:
_write_json_atomic(result, output_path)
def process_logs(file_path, target_codes: list[int], output_path: str = None):
targets = {int(c) for c in target_codes}
if not targets:
raise ValueError("target_codes must contain at least one status code")
try:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
result = count_matching(f, targets)
except OSError as e:
print(f"error: cannot read {file_path!r}: {e.strerror or e}", file=sys.stderr)
return None
emit(result, output_path)
return result
def main(argv=None) -> int:
p = argparse.ArgumentParser(prog="log-analyzer")
p.add_argument("file_path")
p.add_argument("--codes", nargs="+", type=int, required=True)
p.add_argument("--output", default=None)
a = p.parse_args(argv)
return 0 if process_logs(a.file_path, a.codes, a.output) is not None else 1
if __name__ == "__main__":
sys.exit(main())
Returning the result dictionary as well as emitting it makes process_logs easy to assert against.
Complexity
- Time: O(N). Each line costs a bounded split, one
int()call, and one set lookup (assuming bounded line length). - Space: O(K). Only the target set, the counter, and the current line plus I/O buffer are held. The file is never loaded in full.
Edge cases and decisions
- Missing or unreadable file: catch
OSError(covers not-found, permission, and directory errors), print a clear message to stderr, returnNone, and let the CLI exit non-zero instead of showing a traceback. - Empty
target_codes: a caller error, so raiseValueErrorrather than quietly reporting zero. Duplicates collapse in the set. - Corrupt bytes:
errors="replace"stops one bad byte from killing a multi-hour run over 10 GB. - Output safety: write JSON to a temp file in the same directory and
os.replaceit, so a crash never leaves half-written JSON.
Testing strategy
- Test
parse_statuswith valid, blank, single-token, and non-numeric inputs. - Test
count_matchingwith lists orio.StringIO: exact versus substring matching (50must not match500), duplicate targets, malformed lines, blank lines, and no matches. - Test
emitby passing anio.StringIOstream, and the JSON path using a temporary directory. - Test
process_logsfor a missing file and for an empty code list.
Common mistakes
- Keeping the substring check and calling the job done.
- Using
readlines()orread(), which loads the entire file. - Leaving parsing, counting, and output tangled together.
- Counting malformed lines as matches, or crashing on them.
- Writing the JSON in place, which risks a truncated file.
Possible extensions
For further speed, read in binary mode and process byte lines, or split the file into byte ranges and count in parallel with multiprocessing, merging the per-code Counter objects at the end. For a stream that never ends, the same count_matching can be fed from sys.stdin.