-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrequestlog.go
More file actions
111 lines (94 loc) · 2.02 KB
/
requestlog.go
File metadata and controls
111 lines (94 loc) · 2.02 KB
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
package dnsproxy
import (
"compress/gzip"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
)
type requestLogWriter struct {
f *os.File
filePath string
lock *sync.Mutex
}
var requestLog *requestLogWriter
func (w *requestLogWriter) Open(filePath string) error {
f, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
if err != nil {
return err
}
w = &requestLogWriter{
f: f,
filePath: filePath,
lock: &sync.Mutex{},
}
return nil
}
func (w *requestLogWriter) Rotate() {
rotatedName := fmt.Sprintf("%s.%s", w.filePath, time.Now().AddDate(0, 0, -1).Format("2006-01-02"))
w.lock.Lock()
defer func() {
w.lock.Unlock()
if serverConfig.CompressRotatedLogs {
gzipFile(rotatedName)
}
}()
w.f.Sync()
w.f.Close()
w.f = nil
os.Rename(w.filePath, rotatedName)
if f, err := os.OpenFile(w.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
w.f = f
}
}
func (w *requestLogWriter) Close() {
w.lock.Lock()
w.f.Sync()
w.f.Close()
w.lock.Unlock()
}
func (w *requestLogWriter) Record(proto, ip string, query, reply []byte) {
values := []string{
time.Now().UTC().Format("2006-01-02T15:04:05-0700"),
csvEscape(serverConfig.ServerName),
proto,
csvEscape(ip),
fmt.Sprintf("%x", query),
fmt.Sprintf("%x", reply),
}
line := []byte(strings.Join(values, ",") + "\n")
os.Stdout.Write(line)
w.lock.Lock()
w.f.Write(line)
w.lock.Unlock()
}
func csvEscape(in string) string {
if in != "" && strings.ContainsAny(in, ",\"\n") {
in = strings.ReplaceAll(in, ",", "__COMMA__")
in = strings.ReplaceAll(in, "\"", "__QUOTE__")
in = strings.ReplaceAll(in, "\n", "__NEWLINE__")
}
return in
}
func gzipFile(name string) error {
gzName := name + ".gz"
in, err := os.Open(name)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(gzName, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return err
}
defer out.Close()
w := gzip.NewWriter(out)
if _, err := io.Copy(w, in); err != nil {
return err
}
w.Close()
os.Remove(name)
return nil
}