Drill

ProblemsPython › monitoring

Count log lines by level

mediummonitoringPython

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.

count_by_level(lines: list<string>) → map<string, int>

Solve it in the editor →

Where you start

def count_by_level(lines: list[str]) -> dict[str, int]:
    

Worked examples

CallResult
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

The same problem in another language

More monitoring problems in Python