This repository has been archived by the owner on Mar 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
246 lines (230 loc) · 5.01 KB
/
main.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
tailer "github.com/nxadm/tail"
"github.com/radovskyb/watcher"
)
const (
fileMode = iota
directoryMode
start
stop
)
var (
tails sync.Map
poll bool
exclude []string
json bool
minLevel int
)
type tailEvent struct {
Op int
File string
}
func init() {
fs := flag.NewFlagSet("config", flag.ContinueOnError)
fs.BoolVar(&poll, "poll", false, "Use polling instead of inotify")
fs.BoolVar(&json, "json", false, "Keep only JSON logs")
fs.IntVar(&minLevel, "minlevel", 0, "Minimum log level")
e := fs.String("exclude", "sasl|config|lock|@|gzip|tgz|gz", "blacklist (sep. by |): excludes any file containing any of those words in their fullpath.")
fs.SetOutput(ioutil.Discard)
fs.Parse(os.Args[1:])
exclude = strings.Split(*e, "|")
}
func main() {
c := make(chan *tailEvent)
ff := filesFromArgs()
go tail(c)
if v, ok := ff[directoryMode]; ok {
go watch(v, c)
}
for _, f := range ff[fileMode] {
c <- &tailEvent{Op: start, File: f}
}
runtime.Goexit()
}
func watchFilter(info os.FileInfo, fullPath string) error {
if info.IsDir() {
return watcher.ErrSkip
}
for _, w := range exclude {
if strings.Contains(fullPath, w) {
return watcher.ErrSkip
}
}
return nil
}
func watch(dirs []string, c chan *tailEvent) {
w := watcher.New()
w.AddFilterHook(watchFilter)
w.FilterOps(watcher.Create, watcher.Write, watcher.Remove)
go func() {
for {
select {
case event := <-w.Event:
switch event.Op {
case watcher.Create, watcher.Write:
_, ok := tails.Load(event.Path)
if !ok {
c <- &tailEvent{Op: start, File: event.Path}
}
case watcher.Remove:
c <- &tailEvent{Op: stop, File: event.Path}
default:
panic(nil)
}
case err := <-w.Error:
panic(err)
case <-w.Closed:
return
}
}
}()
for _, d := range dirs {
if err := w.AddRecursive(d); err != nil {
panic(err)
}
}
if err := w.Start(time.Millisecond * 100); err != nil {
panic(err)
}
}
func tail(c chan *tailEvent) {
for evt := range c {
switch evt.Op {
case start:
go func() {
t, err := tailer.TailFile(evt.File, tailer.Config{Poll: poll, Follow: true, ReOpen: true, Location: &tailer.SeekInfo{Whence: io.SeekEnd}, Logger: tailer.DiscardingLogger})
if err != nil {
panic(err)
}
tails.Store(evt.File, t)
for line := range t.Lines {
log(t.Filename, line.Text)
}
}()
case stop:
v, ok := tails.Load(evt.File)
if ok {
v.(*tailer.Tail).Stop()
tails.Delete(evt.File)
}
default:
panic(nil)
}
}
}
func filesFromArgs() map[int][]string {
var filePerMode map[int][]string = make(map[int][]string)
for _, f := range os.Args[1:] {
if strings.HasPrefix(f, "/") {
mode := fileMode
if isDir(f) {
mode = directoryMode
}
filePerMode[mode] = append(filePerMode[mode], f)
}
}
return filePerMode
}
func isDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
func log(file, message string) {
if len(message) == 0 {
return
}
j := isJson(message)
if json && !j {
return
}
level, label := detectLevel(message)
if level < minLevel {
return
}
if !j {
message = strconv.Quote(message)
}
date := time.Now().Format(time.RFC3339)
component, subcomponent := components(file)
fmt.Printf("{\"date\":\"%s\",\"component\": \"%s\",\"subcomponent\":\"%s\",\"level\":\"%s\",\"file\":%q,\"message\":%s}\n", date, component, subcomponent, label, file, message)
}
func detectLevel(message string) (int, string) {
level := 100
label := "unknown"
message = strings.ToLower(message)
debug := []string{"debug"}
info := []string{"info", "log", "get", "post", "processing", "starting", "started", "completed", "success", "saving", "saved", "creating", "created"}
notice := []string{"notice"}
warn := []string{"warn"}
err := []string{"error", "failed"}
fatal := []string{"fatal", "emerg"}
for _, w := range debug {
if strings.Contains(message, w) {
level = 1
label = "debug"
break
}
}
for _, w := range info {
if strings.Contains(message, w) {
level = 2
label = "info"
break
}
}
for _, w := range notice {
if strings.Contains(message, w) {
level = 3
label = "notice"
break
}
}
for _, w := range warn {
if strings.Contains(message, w) {
level = 4
label = "warning"
break
}
}
for _, w := range err {
if strings.Contains(message, w) {
level = 5
label = "error"
break
}
}
for _, w := range fatal {
if strings.Contains(message, w) {
level = 6
label = "fatal"
break
}
}
return level, label
}
func components(file string) (string, string) {
parts := strings.Split(file, "/")
component := parts[len(parts)-2:][0]
subcomponent := parts[len(parts)-1:][0]
subcomponent = strings.TrimSuffix(subcomponent, filepath.Ext(subcomponent))
return component, subcomponent
}
func isJson(s string) bool {
//cheap detection; must be good / fastest for such logs parsing
return s[:1] == "{" && s[len(s)-1:] == "}"
}