NASutils Knowledge BaseUnofficialPolski

Go · lesson 28 of 30 · Tools for the NASSummarise a log

SplitN cuts a line into at most four parts, so the last one is the whole message. A map counts the levels.

Programming on the NAS › Go in 30 lessons

28-log-summary.go Download 28-log-summary.go

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	f, err := os.Open("nas.log")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer f.Close()

	count := map[string]int{}
	lines := bufio.NewScanner(f)
	for lines.Scan() {
		part := strings.SplitN(lines.Text(), " ", 4) // date, time, level, text
		if len(part) < 4 {
			continue
		}
		count[part[2]]++
		if part[2] == "ERROR" {
			fmt.Println(part[0], part[3])
		}
	}
	if err := lines.Err(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Printf("%d info, %d warnings, %d errors\n", count["INFO"], count["WARN"], count["ERROR"])
}

Terminal

$ ./28-log-summary
2027-01-04 share Documents is full
2027-01-05 backup stopped: no space
2027-01-06 disk 3 read error
6 info, 3 warnings, 3 errors

Exercise

Take the file name as an argument.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.