Problems › Python › monitoring
Count log lines by level
A log summariser reports how many lines came in at each level. The level is the first word on the line, and the file is not always tidy.
- The level is the first whitespace-separated word, reported in upper case.
- Lines that are empty or only whitespace are skipped.
- Levels that never appear are not in the result.
count_by_level(lines: list<string>) → map<string, int>
Where you start
def count_by_level(lines: list[str]) -> dict[str, int]:
Worked examples
| Call | Result |
|---|---|
count_by_level(["ERROR disk full", "warn retrying", "ERROR timeout"]) | {"ERROR": 2, "WARN": 1} |
count_by_level(["INFO ok"]) | {"INFO": 1} |
count_by_level(["", " "]) | {} |
count_by_level(["DEBUG"]) | {"DEBUG": 1} |
Hint
Trim the line, take everything up to the first space, upper-case it.
Reference solution in Python
def count_by_level(lines: list[str]) -> dict[str, int]:
result = {}
for line in lines:
parts = line.split()
if not parts:
continue
level = parts[0].upper()
result[level] = result.get(level, 0) + 1
return result