Blame view

main.go 4.37 KB
a99c98307   Marko Tikvić   first commit
1
2
3
  package gologger
  
  import (
a7081e581   Marko Tikvić   pretty print json
4
5
  	"bytes"
  	"encoding/json"
a99c98307   Marko Tikvić   first commit
6
  	"fmt"
df74f4a7e   Marko Tikvić   new filename format
7
  	"net/http"
cccb4b47c   Marko Tikvić   log http response
8
  	"net/http/httputil"
a99c98307   Marko Tikvić   first commit
9
  	"os"
e025a8738   Marko Tikvić   platform agnostic...
10
  	"path/filepath"
98708cdaf   Marko Tikvić   new version, does...
11
  	"runtime"
aa60a45ee   Marko Tikvić   changed log file ...
12
  	"strings"
3ba7b5695   Marko Tikvić   added mutex locks...
13
  	"sync"
baa4468b7   Marko Tikvić   Comments go befor...
14
  	"time"
a99c98307   Marko Tikvić   first commit
15
  )
b45f88e17   Marko Tikvić   more readable dat...
16
  const dateTimeFormat = "2006-01-02 15:04:05"
92485819d   Marko Tikvić   lint
17
  // Block ...
434e7da25   Marko Tikvić   changed initializ...
18
19
20
21
22
23
24
  const (
  	MaxLogSize5MB   int64 = 5 * 1024 * 1024
  	MaxLogSize1MB   int64 = 1 * 1024 * 1024
  	MaxLogSize500KB int64 = 500 * 1024
  	MaxLogSize100KB int64 = 100 * 1024
  	MaxLogSize512B  int64 = 512
  )
a99c98307   Marko Tikvić   first commit
25

92485819d   Marko Tikvić   lint
26
  // Logger ...
5eaa49d2a   Marko Tikvić   new design; allow...
27
  type Logger struct {
98cf2ceeb   Marko Tikvić   new interaface; a...
28
29
  	mu         *sync.Mutex
  	outputFile *os.File
23ce66f0f   Marko Tikvić   optional init par...
30

98cf2ceeb   Marko Tikvić   new interaface; a...
31
  	outputFileName string
3e936a3c2   Marko Tikvić   output file name ...
32
  	fullName       string
98cf2ceeb   Marko Tikvić   new interaface; a...
33
  	maxFileSize    int64
df74f4a7e   Marko Tikvić   new filename format
34
35
  
  	splitCount int
c138614d9   Marko Tikvić   output directory ...
36
37
  
  	directory string
a99c98307   Marko Tikvić   first commit
38
  }
92485819d   Marko Tikvić   lint
39
  // New ...
c138614d9   Marko Tikvić   output directory ...
40
  func New(name, dir string, maxFileSize int64) (logger *Logger, err error) {
5eaa49d2a   Marko Tikvić   new design; allow...
41
  	logger = &Logger{}
23ce66f0f   Marko Tikvić   optional init par...
42

b45f88e17   Marko Tikvić   more readable dat...
43
  	logger.outputFileName = name
98cf2ceeb   Marko Tikvić   new interaface; a...
44
45
  	logger.mu = &sync.Mutex{}
  	logger.maxFileSize = maxFileSize
c138614d9   Marko Tikvić   output directory ...
46
  	logger.directory = dir
a99c98307   Marko Tikvić   first commit
47

c138614d9   Marko Tikvić   output directory ...
48
  	err = os.Mkdir(dir, os.ModePerm)
98cf2ceeb   Marko Tikvić   new interaface; a...
49
50
  	if err != nil {
  		if !os.IsExist(err) {
5eaa49d2a   Marko Tikvić   new design; allow...
51
  			return nil, err
a99c98307   Marko Tikvić   first commit
52
53
  		}
  	}
b45f88e17   Marko Tikvić   more readable dat...
54
55
  	date := strings.Replace(time.Now().Format(dateTimeFormat), ":", ".", -1)
  	logger.outputFileName += " " + date
3e936a3c2   Marko Tikvić   output file name ...
56
  	logger.fullName = logger.outputFileName + ".txt"
c138614d9   Marko Tikvić   output directory ...
57
58
  	path := filepath.Join(dir, logger.fullName)
  	if logger.outputFile, err = os.Create(path); err != nil {
98cf2ceeb   Marko Tikvić   new interaface; a...
59
  		return nil, err
e025a8738   Marko Tikvić   platform agnostic...
60
  	}
5eaa49d2a   Marko Tikvić   new design; allow...
61
  	return logger, nil
98708cdaf   Marko Tikvić   new version, does...
62
  }
92485819d   Marko Tikvić   lint
63
  // Log ...
df74f4a7e   Marko Tikvić   new filename format
64
  func (l *Logger) Log(format string, v ...interface{}) {
372beaf62   Marko Tikvić   refactored if sta...
65
66
67
68
69
70
71
72
  	if l.outputFile == nil {
  		return
  	}
  
  	l.mu.Lock()
  	defer l.mu.Unlock()
  
  	msg := fmt.Sprintf(format, v...)
b45f88e17   Marko Tikvić   more readable dat...
73
74
  	s := time.Now().Format(dateTimeFormat) + ": " + msg + "
  "
372beaf62   Marko Tikvić   refactored if sta...
75
76
  	if l.shouldSplit(len(s)) {
  		l.split()
23ce66f0f   Marko Tikvić   optional init par...
77
  	}
372beaf62   Marko Tikvić   refactored if sta...
78
  	l.outputFile.WriteString(s)
98708cdaf   Marko Tikvić   new version, does...
79
  }
92485819d   Marko Tikvić   lint
80
81
82
  // Print ...
  func (l *Logger) Print(format string, v ...interface{}) {
  	msg := fmt.Sprintf(format, v...)
b45f88e17   Marko Tikvić   more readable dat...
83
84
  	fmt.Printf("%s: %s
  ", time.Now().Format(dateTimeFormat), msg)
92485819d   Marko Tikvić   lint
85
86
87
88
89
90
91
  }
  
  // PrintTrace ...
  func (l *Logger) PrintTrace(format string, v ...interface{}) {
  	_, file, line, _ := runtime.Caller(1)
  
  	msg := fmt.Sprintf(format, v...)
b45f88e17   Marko Tikvić   more readable dat...
92
93
  	fmt.Printf("%s: %s %d: %s
  ", time.Now().Format(dateTimeFormat), file, line, msg)
92485819d   Marko Tikvić   lint
94
95
96
97
98
99
100
101
102
103
104
105
106
  }
  
  // Trace ...
  func (l *Logger) Trace(format string, v ...interface{}) {
  	if l.outputFile == nil {
  		return
  	}
  
  	l.mu.Lock()
  	defer l.mu.Unlock()
  
  	_, file, line, _ := runtime.Caller(1)
  	msg := fmt.Sprintf(format, v...)
b45f88e17   Marko Tikvić   more readable dat...
107
108
  	s := fmt.Sprintf("%s: %s %d: %s
  ", time.Now().Format(dateTimeFormat), file, line, msg)
92485819d   Marko Tikvić   lint
109
110
111
112
113
114
115
116
117
118
119
120
121
122
  
  	if l.shouldSplit(len(s)) {
  		l.split()
  	}
  	l.outputFile.WriteString(s)
  }
  
  // PrintAndTrace ...
  func (l *Logger) PrintAndTrace(format string, v ...interface{}) {
  	l.Print(format, v)
  	l.Trace(format, v)
  }
  
  // LogHTTPRequest ...
093191eb2   Marko Tikvić   much cleaner, muc...
123
  func (l *Logger) LogHTTPRequest(req *http.Request, userID string) string {
1f7fbc601   Marko Tikvić   logging user ID
124
125
  	if userID == "" {
  		userID = "-"
372beaf62   Marko Tikvić   refactored if sta...
126
  	}
df74f4a7e   Marko Tikvić   new filename format
127

372beaf62   Marko Tikvić   refactored if sta...
128
  	var b strings.Builder
093191eb2   Marko Tikvić   much cleaner, muc...
129

372beaf62   Marko Tikvić   refactored if sta...
130
131
132
  	b.WriteString("Request:
  ")
  	// CLF-like header
b45f88e17   Marko Tikvić   more readable dat...
133
134
  	fmt.Fprintf(&b, "%s %s %s
  ", req.RemoteAddr, userID, time.Now().Format(dateTimeFormat))
cccb4b47c   Marko Tikvić   log http response
135

093191eb2   Marko Tikvić   much cleaner, muc...
136
137
138
139
  	body, err := httputil.DumpRequest(req, true)
  	if err != nil {
  		fmt.Fprintf(os.Stderr, "%v
  ", err)
cccb4b47c   Marko Tikvić   log http response
140
  	}
a7081e581   Marko Tikvić   pretty print json
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
  
  	const sepStr = "\r
  \r
  "
  	sepIndex := bytes.Index(body, []byte(sepStr))
  	if sepIndex == -1 {
  		b.WriteString(string(body) + "
  
  ")
  	} else {
  		sepIndex += len(sepStr)
  		payload, _ := printJSON(body[sepIndex:])
  		b.WriteString(string(body[:sepIndex]) + string(payload) + "
  
  ")
  	}
372beaf62   Marko Tikvić   refactored if sta...
157

093191eb2   Marko Tikvić   much cleaner, muc...
158
159
  	return b.String()
  }
372beaf62   Marko Tikvić   refactored if sta...
160

feba66094   Marko Tikvić   split line constant
161
  const splitLine = "=============================================================="
92485819d   Marko Tikvić   lint
162
  // LogHTTPResponse ...
093191eb2   Marko Tikvić   much cleaner, muc...
163
  func (l *Logger) LogHTTPResponse(status int, duration time.Duration, size int) string {
feba66094   Marko Tikvić   split line constant
164
165
166
167
  	return fmt.Sprintf("Response:
  %d %v %dB
  %s
  ", status, duration, size, splitLine)
cccb4b47c   Marko Tikvić   log http response
168
  }
92485819d   Marko Tikvić   lint
169
  // CombineHTTPLogs ...
093191eb2   Marko Tikvić   much cleaner, muc...
170
  func (l *Logger) CombineHTTPLogs(in string, out string) {
372beaf62   Marko Tikvić   refactored if sta...
171
172
173
  	if l.outputFile == nil {
  		return
  	}
df74f4a7e   Marko Tikvić   new filename format
174

372beaf62   Marko Tikvić   refactored if sta...
175
176
  	l.mu.Lock()
  	defer l.mu.Unlock()
093191eb2   Marko Tikvić   much cleaner, muc...
177
  	msg := in + out
372beaf62   Marko Tikvić   refactored if sta...
178
179
  	if l.shouldSplit(len(msg)) {
  		l.split()
98708cdaf   Marko Tikvić   new version, does...
180
  	}
372beaf62   Marko Tikvić   refactored if sta...
181
  	l.outputFile.WriteString(msg)
98708cdaf   Marko Tikvić   new version, does...
182
  }
92485819d   Marko Tikvić   lint
183
  // Close ...
c138614d9   Marko Tikvić   output directory ...
184
  func (l *Logger) Close() error {
372beaf62   Marko Tikvić   refactored if sta...
185
  	if l.outputFile == nil {
c138614d9   Marko Tikvić   output directory ...
186
  		return nil
372beaf62   Marko Tikvić   refactored if sta...
187
  	}
c138614d9   Marko Tikvić   output directory ...
188
  	return l.outputFile.Close()
a99c98307   Marko Tikvić   first commit
189
  }
c138614d9   Marko Tikvić   output directory ...
190
  func (l *Logger) split() error {
372beaf62   Marko Tikvić   refactored if sta...
191
  	if l.outputFile == nil {
c138614d9   Marko Tikvić   output directory ...
192
  		return nil
372beaf62   Marko Tikvić   refactored if sta...
193
  	}
98cf2ceeb   Marko Tikvić   new interaface; a...
194
195
196
  	// close old file
  	err := l.outputFile.Close()
  	if err != nil {
c138614d9   Marko Tikvić   output directory ...
197
  		return err
98cf2ceeb   Marko Tikvić   new interaface; a...
198
  	}
df74f4a7e   Marko Tikvić   new filename format
199

98cf2ceeb   Marko Tikvić   new interaface; a...
200
  	// open new file
c138614d9   Marko Tikvić   output directory ...
201
202
203
  	l.splitCount++
  	path := filepath.Join(l.directory, l.outputFileName+fmt.Sprintf("(%d)", l.splitCount)+".txt")
  	l.outputFile, err = os.Create(path)
a99c98307   Marko Tikvić   first commit
204

c138614d9   Marko Tikvić   output directory ...
205
  	return err
a99c98307   Marko Tikvić   first commit
206
  }
98cf2ceeb   Marko Tikvić   new interaface; a...
207
208
209
  func (l *Logger) shouldSplit(nextEntrySize int) bool {
  	stats, _ := l.outputFile.Stat()
  	return int64(nextEntrySize) >= (l.maxFileSize - stats.Size())
a99c98307   Marko Tikvić   first commit
210
  }
a7081e581   Marko Tikvić   pretty print json
211
212
213
214
215
216
  
  func printJSON(in []byte) (out []byte, err error) {
  	var buf bytes.Buffer
  	err = json.Indent(&buf, in, "", "    ")
  	return buf.Bytes(), err
  }