Drill

ProblemsGo › monitoring

Count log lines by level

mediummonitoringHash mapsStringsParsingGo

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>

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.

Solve it in Python →

Where you start

func countByLevel(lines []string) map[string]int {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More monitoring problems in Go