Bitpath

Boss lesson · Unit 07

A log report

Turn raw lines of text into a ranked report, with tests.

13 exercisesabout 3 min

What you practise

  • Lines of text parsed into structs, then counted, grouped and ranked into a report, with tests

Try a question from this lesson

Pick one

A server writes lines such as this one, and you want a report of what went wrong. SplitN splits at spaces but stops after 3 pieces. What prints?

Go
line := "09:15 ERROR db timeout"
parts := strings.SplitN(line, " ", 3)
fmt.Println(len(parts), parts[2])
Hint

After two cuts there are three pieces, and no more cuts are made. What is left in the last piece?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The plan

Raw text is hard to work with, so step one is to turn each line into a struct.

Then: count the entries per level in a map, copy the counts into a slice, sort it, and print the report.

Parse, count, sort, print. Each step is a few lines you already know how to write, and the parser gets a table-driven test.

Go
// one line of the log:
//   09:15 ERROR db timeout

type Entry struct {
  Time  string // "09:15"
  Level string // "ERROR"
  Msg   string // "db timeout"
}

Concept

Ranking the counts

A map has no order, so it cannot be ranked as it is.

Copy it into a slice of small structs, one per level, then sort the slice by count, biggest first.

Map, then slice, then sort: this is the standard way to get a "most common first" list out of counts.

Go
type Stat struct {
  Level string
  N     int
}

stats := []Stat{}
for level, n := range counts {
  stats = append(stats, Stat{level, n})
}
sort.Slice(stats, func(i, j int) bool {
  return stats[i].N > stats[j].N
})

10 more exercises in the app

  • 1× fill the blanks
  • 4× type the answer
  • 3× multiple choice
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy