-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogcmd.go
66 lines (53 loc) · 996 Bytes
/
logcmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/nxadm/tail"
)
func (l *LogCmd) Run(config Config) error {
logPath := filepath.Join(config.StateRoot, appLogFileName)
lines, err := tailFile(logPath, l.LogLines)
if err != nil {
return fmt.Errorf("error reading log file: %w", err)
}
if len(lines) == 0 {
fmt.Println("Log is empty")
return nil
}
for _, line := range lines {
fmt.Println(line)
}
return nil
}
func tailFile(path string, maxLines int) ([]string, error) {
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
t, err := tail.TailFile(
path,
tail.Config{
Follow: false,
Location: nil,
},
)
if err != nil {
return nil, err
}
defer func() {
_ = t.Stop()
}()
// Collect the lines in a ring buffer.
lines := []string{}
for line := range t.Lines {
lines = append(lines, line.Text)
if len(lines) > maxLines {
lines = lines[1:]
}
}
return lines, nil
}