-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtail.go
102 lines (76 loc) · 1.57 KB
/
tail.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
package main
import (
"time"
"github.com/apex/log"
"github.com/astaxie/beego/logs"
"github.com/hpcloud/tail"
)
type CollectConf struct {
LogPath string `json:"path"`
Topic string `json:"topic"`
}
type TailObj struct {
tail *tail.Tail
conf CollectConf
}
type TextMsg struct {
Msg string
Topic string
}
type TailObjMgr struct {
tailsObjs []*TailObj
msgChan chan *TextMsg
}
var (
tailObjMgr *TailObjMgr
)
func GetOneLine() (msg *TextMsg) {
msg = <-tailObjMgr.msgChan
return
}
func InitTail(conf []CollectConf, chanSize int) (err error) {
// 初始化管道
tailObjMgr = &TailObjMgr{
msgChan: make(chan *TextMsg, chanSize),
}
// 容错处理
if len(conf) == 0 {
logs.Error("invaild config for log collect, conf:%v", conf)
return
}
for _, v := range conf {
obj := &TailObj{
conf: v,
}
tails, tailError := tail.TailFile(v.LogPath, tail.Config{
ReOpen: true,
Follow: true,
Location: &tail.SeekInfo{Offset: 0, Whence: 2},
MustExist: false,
Poll: true,
})
if tailError != nil {
log.Errorf("tailf occurs errors, error: %v", tailError)
return tailError
}
obj.tail = tails
tailObjMgr.tailsObjs = append(tailObjMgr.tailsObjs, obj)
go ReadFromTail(obj)
}
return
}
func ReadFromTail(tailObj *TailObj) {
for true {
line, ok := <-tailObj.tail.Lines
if !ok {
logs.Warn("tail file close reopen, filename:%s\n", tailObj.tail.Filename)
time.Sleep(1000 * time.Millisecond)
continue
}
textMsg := &TextMsg{
Msg: line.Text,
Topic: tailObj.conf.Topic,
}
tailObjMgr.msgChan <- textMsg
}
}