-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathlog.go
103 lines (87 loc) · 1.83 KB
/
log.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
package main
import (
"bytes"
"fmt"
"log"
"sync"
"time"
)
// TODO: put logs from different servers into a buffer and print one at at time
func tailLog(servers []*Server, beginLineNum int) {
output := make(chan output)
go outputLogs(output)
for _, serv := range servers {
go func(serv *Server) {
serv.initPathes()
session := serv.getSession()
logger := NewLogger(output, fmt.Sprintf("========================\n%s", serv))
session.Stdout = logger
session.Stderr = logger
if err := session.Start(fmt.Sprintf("tail -f -n %d %s", beginLineNum, serv.LogPath())); err != nil {
exitf("tail -f harp/%s/app.log error: %s", cfg.App, err)
}
// TODO: close session before quitting program
}(serv)
}
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
type Logger struct {
// data []byte
prefix []byte
mutex sync.Mutex
Buffer bytes.Buffer
output chan output
}
type output struct {
data []byte
prefix []byte
}
func NewLogger(outputc chan output, prefix string) (l *Logger) {
l = &Logger{}
l.output = outputc
l.prefix = []byte(prefix)
ticker := time.NewTicker(time.Second * 3)
go func() {
for {
<-ticker.C
l.mutex.Lock()
data := l.Buffer.Bytes()
l.Buffer.Reset()
l.mutex.Unlock()
go func() {
if len(data) == 0 {
return
}
l.output <- output{data, l.prefix}
}()
}
}()
return l
}
func (l *Logger) Write(data []byte) (n int, err error) {
l.mutex.Lock()
defer l.mutex.Unlock()
n, err = l.Buffer.Write(data)
if l.Buffer.Len() < 1024 {
return
}
data = l.Buffer.Bytes()
l.Buffer.Reset()
go func() {
l.output <- output{data, l.prefix}
}()
return
}
func outputLogs(outputc chan output) {
var old output
for {
output := <-outputc
if !bytes.Equal(output.prefix, old.prefix) {
log.Print(string(output.prefix))
}
log.Print(string(output.data))
old = output
}
}