Sobes.tech
Junior — Middle

How can you get the last ten lines from a log file?

sobes.tech AI

Answer from AI

In Go, to get the last ten lines from a log file, you can read the file line by line and store the last 10 lines in a circular buffer (for example, a fixed-size slice). This is memory-efficient and does not require loading the entire file.

Example:

package main

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

func tail(filename string, n int) ([]string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	lines := make([]string, 0, n)
	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		if len(lines) == n {
			lines = lines[1:]
		}
		lines = append(lines, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return lines, nil
}

func main() {
	lines, err := tail("logfile.log", 10)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	for _, line := range lines {
		fmt.Println(line)
	}
}

This code reads the file line by line, keeping only the last 10 lines.

How can you get the last ten lines from a log file… - sobes.tech