Let me start by reading the SPEC.md file to understand what the logstat tool should do.
arguments
{"path":"SPEC.md"}
3 lines, 23 B
output
# logstat specification
`logstat` reads log records, filters them by severity, and prints one of three summaries.
This document is the whole interface. Anything it does not describe is not part of the
tool, and anything it does describe is checked.
## Invocation
```
python3 logstat.py <subcommand> [options] [FILE]
```
`logstat.py` stays at the top of this directory and stays runnable by a plain
`python3 logstat.py`. `<subcommand>` is one of `count`, `top`, `span`, spelled in lower
case.
#!/usr/bin/env python3
"""logstat: filter log records by severity and print one of three summaries.
Nothing here is implemented. SPEC.md is the interface, down to the column widths and the
exit codes. Keep this file at this path and keep it runnable as `python3 logstat.py`.
"""
from __future__ import annotations
import sys
def main(argv: list[str]) -> int:
"""Run the tool and return the process exit code.
Args:
Let me analyze the specification carefully and implement the logstat tool. This is a complex specification with many details. Let me break it down:
1. **Invocation**: `python3 logstat.py <subcommand> [options] [FILE]`
- Subcommands: `count`, `top`, `span`
- FILE is optional (reads from stdin if absent)
- Options can appear before or after FILE
2. **Options**:
- `--min-level LEVEL`: Accepted by all subcommands. Levels: DEBUG, INFO, WARN, ERROR, FATAL. Default: DEBUG
- `--number N`: Accepted by `top` only. Positive integer. Default: 3. Error if used with `count` or `span`
- Both `--min-level VALUE` and `--min-level=VALUE` accepted, same for `--number`
- Unknown options (starting with `-` except `-` alone) are usage errors
3. **Severity order**: DEBUG < INFO < WARN < ERROR < FATAL
4. **Record format**: `TIMESTAMP|LEVEL|SERVICE|MESSAGE`
- Split on `|` at first three occurrences only
- TIMESTAMP: exactly 20 chars, format `YYYY-MM-DDTHH:MM:SSZ`, valid date/time
- LEVEL: exactly one of DEBUG, INFO, WARN, ERROR, FATAL
- SERVICE: not empty
- MESSAGE: everything after third `|`, can contain `|`, can be empty
- At least 3 `|` characters required
- No stripping before checks
5. **Blank lines**: Empty or only spaces/tabs - ignored completely
6. **Malformed input**: Fatal, detected before anything printed
- Exit 4, stderr: `logstat: malformed record on line N` (1-based, includes blank lines)
- Reads entire input before producing summary
7. **Exit codes**:
- 0: success
- 2: usage error
- 3: input error (file cannot be opened/read)
- 4: malformed line
- 5: span with zero records
8. **Subcommand: count**
- One line per level from --min-level to FATAL in canonical order, then TOTAL
- Format: label (5 chars left-justified) + space + count (right-justified, width = digits in TOTAL)
- Empty input: six lines with 0 counts
9. **Subcommand: top**
- Services with most surviving records, at most --number lines
- Order: count descending, then service name ascending (Unicode code point)
- Column widths from printed lines only
- Format: service name (left-justified, width = longest printed) + space + count (right-justified, width = largest count printed)
- No records: prints nothing, exits 0
10. **Subcommand: span**
- Three lines: first, last, secs
- Labels left-justified in 5-char field
- Earliest/latest by timestamp value
- secs = difference in whole seconds
- No records: stderr `logstat: no records matched`, exit 5
11. **Output rules**: Every line ends in exactly one newline, no header, no trailing blank line
Now let me implement this step by step.
First, I'll create a plan:
1. Parse command line arguments
2. Read input (file or stdin)
3. Parse records, validate format
4. Filter by min-level
5. Execute subcommand
6. Output results
Let me start implementing.
content
#!/usr/bin/env python3
"""logstat: filter log records by severity and print one of three summaries.
Nothing here is implemented. SPEC.md is the interface, down to the column widths and the
exit codes. Keep this file at this path and keep it runnable as `python3 logstat.py`.
"""
from __future__ import annotations
import sys
import re
from datetime import datetime
from collections import Counter
from typing import Optional, List, Tuple
LEVELS = ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"]
LEVEL_ORDER = {level: i for i, level in enumerate(LEVELS)}
Let me test some edge cases with the message containing `|` and other things.
content
2026-03-01T09:15:04Z|INFO|gateway|message with | pipe
2026-03-01T09:16:00Z|INFO|checkout|another | message | with pipes
2026-03-01T09:17:00Z|INFO|gateway|empty message after|
2026-03-01T09:18:00Z|INFO|gateway|trailing space