Search a Log File

Lab Python Advanced 30 points

Read log lines until END and write them to app.log. Lines look like LEVEL message. Reading the file, print the count of each level (sorted by level) as LEVEL: N, then every ERROR message.

Input

Log lines, then END.

Output

The counts, then the error messages.

Example

Input

INFO started
ERROR disk full
WARN slow
ERROR timeout
INFO stopped
END

Output

ERROR: 2
INFO: 2
WARN: 1
disk full
timeout
Sample input available Sample output available
Editor
Python

Hints

str.partition(" ") splits into (before, separator, after) once.

A Counter starts every key at 0.

Solution explanation

Scanning logs is one of the most common real-world uses of Python.

Show solution
from collections import Counter

with open("app.log", "w") as f:
    while (line := input()) != "END":
        f.write(line + "\n")

counts = Counter()
errors = []
with open("app.log") as f:
    for line in f:
        level, _, message = line.rstrip("\n").partition(" ")
        counts[level] += 1
        if level == "ERROR":
            errors.append(message)
for level in sorted(counts):
    print(f"{level}: {counts[level]}")
for message in errors:
    print(message)
Output
Answer
HOME LEARN COMMUNITY DASHBOARD