-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.go
224 lines (190 loc) · 4.52 KB
/
output.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
package main
import (
"bufio"
"bytes"
"compress/zlib"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
const (
gelfChunkSize = 1300
)
var (
gelfMsgID uint64
)
func openOrStdout(filename string, timeFormat string) *os.File {
outName := filename
if timeFormat != "" {
outName = fmt.Sprintf("%s.%s", filename, time.Now().Format(timeFormat))
}
out, err := os.OpenFile(outName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0600)
if nil != err {
log.Printf("[minisv] Error opening output log (%s), using stdout: %v\n",
outName, err)
return os.Stdout
}
return out
}
func sendGrayLogUDPMessage(message string, serviceName string, graylog grayLogConfig) error {
if graylog.socket == nil {
return nil
}
hostname, _ := os.Hostname()
if hostname == "" {
hostname = "minisv" // graylog rejects messages without hostname
}
msg := map[string]interface{}{
"version": "1.1",
"host": hostname,
"short_message": message,
"timestamp": float64(time.Now().UnixNano()) / 1000000000.0,
"level": graylog.Level,
"_service": serviceName,
}
for k, v := range graylog.AddFields {
msg[k] = v
}
data, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("error encoding graylog json message: %w", err)
}
if len(data) > 1400 { // with IP and UDP headers this will be more than 1500 bytes
var buf bytes.Buffer
cdata := zlib.NewWriter(&buf)
_, err := cdata.Write(data)
if err == nil {
err = cdata.Close()
if err == nil {
data = buf.Bytes()
}
}
}
// if message is small enough
if len(data) < 1401 {
_, err = graylog.socket.Write(data)
if err != nil {
return fmt.Errorf("error sending graylog UDP message: %w", err)
}
return nil
}
if len(data) > 65000 { // what is actual limit for graylog/udp?..
return fmt.Errorf("log message is too long for graylog (%d bytes)", len(data))
}
// if no we need to send in chunks...
header := [12]byte{0x1e, 0x0f}
binary.BigEndian.PutUint64(header[2:10], atomic.AddUint64(&gelfMsgID, 1))
chunks := byte(len(data) / gelfChunkSize)
if len(data)%gelfChunkSize > 0 {
chunks++
}
header[11] = chunks
for i := 0; i < len(data); i += gelfChunkSize {
if i+gelfChunkSize < len(data) {
_, err = graylog.socket.Write(append(header[:], data[i:i+gelfChunkSize]...))
} else {
_, err = graylog.socket.Write(append(header[:], data[i:]...))
}
if err != nil {
return fmt.Errorf("error sending graylog UDP message: %w", err)
}
header[10]++
}
return nil
}
func logWithRotation(filename string, timeSuffixFormat string, rotate chan bool,
timeFormat string, serviceName string, graylog grayLogConfig) io.WriteCloser {
reader, writer := io.Pipe()
bufread := bufio.NewReader(reader)
bufchan := make(chan string, 100)
go func() {
defer close(bufchan)
var err error
var str string
for nil == err {
str, err = bufread.ReadString('\n')
if nil == err {
bufchan <- str
}
}
}()
go func() {
out := openOrStdout(filename, timeSuffixFormat)
for {
select {
case <-rotate:
if os.Stdout != out {
if err := out.Close(); nil != err {
log.Println("Error closing output: ", err)
}
}
out = openOrStdout(filename, timeSuffixFormat)
case str, ok := <-bufchan:
if !ok {
if os.Stdout != out {
if err := out.Close(); nil != err {
log.Println("Error closing output: ", err)
}
}
return
}
var err error
if timeFormat != "" {
_, err = out.WriteString(
fmt.Sprintf("%s: %s", time.Now().Format(timeFormat), str))
} else {
_, err = out.WriteString(str)
}
if nil != err {
log.Println("Error writing to output file: ", err)
}
sendGrayLogUDPMessage(str, serviceName, graylog)
}
}
}()
return writer
}
func rotateLogs() {
config := aConfig.Load()
for name := range config.Tasks {
if !config.Tasks[name].OneTime {
select {
case config.Tasks[name].fSignal <- true:
default:
}
}
}
}
func rotateOnHUP() {
hupChan := make(chan os.Signal, 1)
signal.Notify(hupChan, syscall.SIGHUP)
for range hupChan {
rotateLogs()
}
}
func rotateEveryPeriod() {
config := aConfig.Load()
if nil == config.LogReopen {
return
}
every := time.Duration(*config.LogReopen)
// if no value present in config
if every == 0 {
return
}
log.Println("Rotate logs every ", every)
// align time in so ugly way :)
time.Sleep(time.Until(time.Now().Truncate(every).Add(every)))
go rotateLogs()
ticker := time.NewTicker(every)
for range ticker.C {
go rotateLogs()
}
}