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>
Go 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
func countByLevel(lines []string) map[string]int {
}
Worked examples
| Call | Result |
|---|---|
countByLevel([]string{"ERROR disk full", "warn retrying", "ERROR timeout"}) | map[string]int{"ERROR": 2, "WARN": 1} |
countByLevel([]string{"INFO ok"}) | map[string]int{"INFO": 1} |
countByLevel([]string{"", " "}) | map[string]int{} |
countByLevel([]string{"DEBUG"}) | map[string]int{"DEBUG": 1} |
Hint
Trim the line, take everything up to the first space, upper-case it.
Reference solution in Go
func countByLevel(lines []string) map[string]int {
result := map[string]int{}
for _, line := range lines {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
result[strings.ToUpper(parts[0])]++
}
return result
}