This repository has been archived by the owner on Jun 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 396
/
logs.go
93 lines (81 loc) · 1.94 KB
/
logs.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/Azure/draft/pkg/draft/draftpath"
"github.com/hpcloud/tail"
"github.com/spf13/cobra"
)
const logsDesc = `This command outputs logs from the draft server to help debug builds.`
type logsCmd struct {
out io.Writer
appName string
buildID string
line uint
tail bool
args []string
home draftpath.Home
}
func newLogsCmd(out io.Writer) *cobra.Command {
lc := &logsCmd{
out: out,
args: []string{"build-id"},
}
cmd := &cobra.Command{
Use: "logs <build-id>",
Short: logsDesc,
Long: logsDesc,
PreRunE: lc.complete,
RunE: func(cmd *cobra.Command, args []string) error {
b, err := getLatestBuildID()
if err != nil {
return fmt.Errorf("cannot get latest build: %v", err)
}
lc.buildID = b
if len(args) > 0 {
lc.buildID = args[0]
}
return lc.run(cmd, args)
},
}
f := cmd.Flags()
f.BoolVar(&lc.tail, "tail", false, "tail the logs file as it's being written")
f.UintVar(&lc.line, "line", 20, "line location to tail from (offset from end of file)")
return cmd
}
func (l *logsCmd) complete(_ *cobra.Command, args []string) error {
l.home = draftpath.Home(homePath())
return nil
}
func (l *logsCmd) run(_ *cobra.Command, _ []string) error {
if l.tail {
return l.tailLogs(int64(l.line))
}
return l.dumpLogs()
}
func (l *logsCmd) dumpLogs() error {
f, err := os.Open(filepath.Join(l.home.Logs(), l.buildID))
if err != nil {
return fmt.Errorf("could not read logs for %s: %v", l.buildID, err)
}
defer f.Close()
io.Copy(l.out, f)
return nil
}
func (l *logsCmd) tailLogs(offset int64) error {
t, err := tail.TailFile(filepath.Join(l.home.Logs(), l.buildID), tail.Config{
Location: &tail.SeekInfo{Offset: -offset, Whence: os.SEEK_END},
Logger: tail.DiscardingLogger,
Follow: true,
ReOpen: true,
})
if err != nil {
return err
}
for line := range t.Lines {
fmt.Fprintln(l.out, line.Text)
}
return t.Wait()
}