forked from jwilder/gohub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logstream.go
122 lines (101 loc) · 2.11 KB
/
logstream.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
120
121
122
package main
import (
"bytes"
"io"
"log"
"os"
)
type Logstreamer struct {
Logger *log.Logger
buf *bytes.Buffer
readLines string
// If prefix == stdout, colors green
// If prefix == stderr, colors red
// Else, prefix is taken as-is, and prepended to anything
// you throw at Write()
prefix string
// if true, saves output in memory
record bool
persist string
// Adds color to stdout & stderr if terminal supports it
colorOkay string
colorFail string
colorReset string
}
func NewLogstreamer(logger *log.Logger, prefix string, record bool) *Logstreamer {
streamer := &Logstreamer{
Logger: logger,
buf: bytes.NewBuffer([]byte("")),
prefix: prefix,
record: record,
persist: "",
colorOkay: "",
colorFail: "",
colorReset: "",
}
if os.Getenv("TERM") == "xterm" {
streamer.colorOkay = "\x1b[32m"
streamer.colorFail = "\x1b[31m"
streamer.colorReset = "\x1b[0m"
}
return streamer
}
func (l *Logstreamer) Write(p []byte) (n int, err error) {
if n, err = l.buf.Write(p); err != nil {
return
}
err = l.OutputLines()
return
}
func (l *Logstreamer) Close() error {
l.Flush()
l.buf = bytes.NewBuffer([]byte(""))
return nil
}
func (l *Logstreamer) Flush() error {
var p []byte
if _, err := l.buf.Read(p); err != nil {
return err
}
l.out(string(p))
return nil
}
func (l *Logstreamer) OutputLines() (err error) {
for {
line, err := l.buf.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
return err
}
l.readLines += line
l.out(line)
}
return nil
}
func (l *Logstreamer) ResetReadLines() {
l.readLines = ""
}
func (l *Logstreamer) ReadLines() string {
return l.readLines
}
func (l *Logstreamer) FlushRecord() string {
buffer := l.persist
l.persist = ""
return buffer
}
func (l *Logstreamer) out(str string) (err error) {
if l.record == true {
l.persist = l.persist + str
}
if l.prefix == "stdout" {
str = l.colorOkay + l.prefix + l.colorReset + " " + str
} else if l.prefix == "stderr" {
str = l.colorFail + l.prefix + l.colorReset + " " + str
} else {
str = l.prefix + str
}
l.Logger.Print(str)
return nil
}