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.
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.
Where you start
public Dictionary<string, int> CountByLevel(List<string> lines) {
}
Worked examples
| Call | Result |
|---|---|
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;
}