-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogs.go
119 lines (104 loc) · 2.4 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package robin
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/hpcloud/tail"
"github.com/rs/zerolog"
)
func Logs(b BatchSystem, jobName string, outputType string) error {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
job, err := findJob(b, jobName)
if err != nil {
return fmt.Errorf("find job: %w", err)
}
logFile := job.OutputFile
if outputType == "err" {
logFile = job.ErrorFile
}
cmd := exec.Command(editor, logFile)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("execute editor: %w", err)
}
return nil
}
func writeLine(consoleWriter zerolog.ConsoleWriter, line string) error {
_, err := consoleWriter.Write([]byte(line))
if err != nil {
_, err = consoleWriter.Out.Write([]byte(line + "\n"))
if err != nil {
return fmt.Errorf("write output: %w", err)
}
}
return nil
}
func Logtail(b BatchSystem, jobName, outputType string, nBytes int) error {
job, err := findJob(b, jobName)
if err != nil {
return fmt.Errorf("find job: %w", err)
}
logFile := job.OutputFile
if outputType == "err" {
logFile = job.ErrorFile
}
location := &tail.SeekInfo{
Offset: 0,
Whence: io.SeekStart,
}
// If the file exists and it is large enough, truncate by seeking
if fi, err := os.Stat(logFile); err == nil {
if fi.Size() > int64(nBytes) {
location = &tail.SeekInfo{
Offset: -int64(nBytes),
Whence: io.SeekEnd,
}
}
}
tailConfig := tail.Config{
Follow: true,
ReOpen: true,
Poll: true, // On many cluster filesystems, inotify doesn't work
Location: location,
Logger: tail.DiscardingLogger,
}
consoleWriter := zerolog.ConsoleWriter{
Out: os.Stdout,
PartsOrder: []string{
zerolog.TimestampFieldName,
zerolog.LevelFieldName,
"stream",
zerolog.MessageFieldName,
},
TimeFormat: time.DateTime,
FieldsExclude: []string{"stream"},
}
t, err := tail.TailFile(logFile, tailConfig)
if err != nil {
return fmt.Errorf("tail file: %w", err)
}
for line := range t.Lines {
if line.Err == io.EOF {
return nil
}
if line.Err != nil {
return fmt.Errorf("tail file: %w", err)
}
// If it is a cut JSON, skip it
if strings.HasSuffix(line.Text, "}") && !strings.HasPrefix(line.Text, "{") {
continue
}
if err = writeLine(consoleWriter, line.Text); err != nil {
return fmt.Errorf("write line: %w", err)
}
}
return nil
}