forked from mintance/nginx-clickhouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (83 loc) · 2.31 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
package main
import (
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/UnitedTraders/nginx-clickhouse/clickhouse"
configParser "github.com/UnitedTraders/nginx-clickhouse/config"
"github.com/UnitedTraders/nginx-clickhouse/nginx"
"github.com/papertrail/go-tail/follower"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
var (
locker sync.Mutex
logs []string
)
var (
linesProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "nginx_clickhouse_lines_processed_total",
Help: "The total number of processed log lines",
})
linesNotProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "nginx_clickhouse_lines_not_processed_total",
Help: "The total number of log lines which was not processed",
})
)
func main() {
// Read config & incoming flags
config := configParser.Read()
// Update config with environment variables if exist
config.SetEnvVariables()
nginxParser, err := nginx.GetParser(config)
go func() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}()
if err != nil {
logrus.Fatal("Can`t parse nginx log format: ", err)
}
logs = []string{}
logrus.Info("Trying to open logfile: " + config.Settings.LogPath)
whenceSeek := io.SeekStart
if config.Settings.SeekFromEnd {
whenceSeek = io.SeekEnd
}
t, err := follower.New(config.Settings.LogPath, follower.Config{
Whence: whenceSeek,
Offset: 0,
Reopen: true,
})
if err != nil {
logrus.Fatal("Can`t tail logfile: ", err)
}
go func() {
for {
time.Sleep(time.Second * time.Duration(config.Settings.Interval))
if len(logs) > 0 {
logrus.Info("Preparing to save ", len(logs), " new log entries.")
locker.Lock()
err := clickhouse.Save(config, nginx.ParseLogs(nginxParser, logs))
if err != nil {
logrus.Error("Can`t save logs: ", err)
linesNotProcessed.Add(float64(len(logs)))
} else {
logrus.Info("Saved ", len(logs), " new logs.")
linesProcessed.Add(float64(len(logs)))
}
logs = []string{}
locker.Unlock()
}
}
}()
// Push new log entries to array
for line := range t.Lines() {
locker.Lock()
logs = append(logs, strings.TrimSpace(line.String()))
locker.Unlock()
}
}