Drill

ProblemsC# › monitoring

Count log lines by level

mediummonitoringHash mapsStringsParsingC#

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>

C# 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

public Dictionary<string, int> CountByLevel(List<string> lines) {
    
}

Worked examples

CallResult
CountByLevel(new List<string> { "ERROR disk full", "warn retrying", "ERROR timeout" })new Dictionary<string, int> { { "ERROR", 2 }, { "WARN", 1 } }
CountByLevel(new List<string> { "INFO ok" })new Dictionary<string, int> { { "INFO", 1 } }
CountByLevel(new List<string> { "", " " })new Dictionary<string, int> { }
CountByLevel(new List<string> { "DEBUG" })new Dictionary<string, int> { { "DEBUG", 1 } }

Hint

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

Reference solution in C#
public Dictionary<string, int> CountByLevel(List<string> lines) {
    var result = new Dictionary<string, int>();
    foreach (var line in lines) {
        var parts = line.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length == 0) continue;
        string level = parts[0].ToUpperInvariant();
        result[level] = result.ContainsKey(level) ? result[level] + 1 : 1;
    }
    return result;
}

The same problem in another language

More monitoring problems in C#