Drill

ProblemsJava › monitoring

Count log lines by level

mediummonitoringHash mapsStringsParsingJava

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.

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

Map<String, Integer> countByLevel(List<String> lines) {
    
}

Worked examples

CallResult
countByLevel(Main.<String>ls("ERROR disk full", "warn retrying", "ERROR timeout"))Main.<String, Integer>mp("ERROR", 2, "WARN", 1)
countByLevel(Main.<String>ls("INFO ok"))Main.<String, Integer>mp("INFO", 1)
countByLevel(Main.<String>ls("", " "))Main.<String, Integer>mp()
countByLevel(Main.<String>ls("DEBUG"))Main.<String, Integer>mp("DEBUG", 1)

Hint

Trim the line, take everything up to the first space, upper-case it.

Reference solution in Java
Map<String, Integer> countByLevel(List<String> lines) {
    Map<String, Integer> result = new LinkedHashMap<>();
    for (String line : lines) {
        String t = line.trim();
        if (t.isEmpty()) continue;
        String level = t.split("\\s+")[0].toUpperCase();
        result.merge(level, 1, Integer::sum);
    }
    return result;
}

The same problem in another language

More monitoring problems in Java