Blame view

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

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

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

b45f88e17   Marko Tikvić   more readable dat...
40
  	logger.outputFileName = name
98cf2ceeb   Marko Tikvić   new interaface; a...
41
42
  	logger.mu = &sync.Mutex{}
  	logger.maxFileSize = maxFileSize
a99c98307   Marko Tikvić   first commit
43

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

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

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

093191eb2   Marko Tikvić   much cleaner, muc...
137
138
139
140
  	body, err := httputil.DumpRequest(req, true)
  	if err != nil {
  		fmt.Fprintf(os.Stderr, "%v
  ", err)
cccb4b47c   Marko Tikvić   log http response
141
  	}
093191eb2   Marko Tikvić   much cleaner, muc...
142
143
144
  	b.WriteString(string(body) + "
  
  ")
372beaf62   Marko Tikvić   refactored if sta...
145

093191eb2   Marko Tikvić   much cleaner, muc...
146
147
  	return b.String()
  }
372beaf62   Marko Tikvić   refactored if sta...
148

feba66094   Marko Tikvić   split line constant
149
  const splitLine = "=============================================================="
92485819d   Marko Tikvić   lint
150
  // LogHTTPResponse ...
093191eb2   Marko Tikvić   much cleaner, muc...
151
  func (l *Logger) LogHTTPResponse(status int, duration time.Duration, size int) string {
feba66094   Marko Tikvić   split line constant
152
153
154
155
  	return fmt.Sprintf("Response:
  %d %v %dB
  %s
  ", status, duration, size, splitLine)
cccb4b47c   Marko Tikvić   log http response
156
  }
92485819d   Marko Tikvić   lint
157
  // CombineHTTPLogs ...
093191eb2   Marko Tikvić   much cleaner, muc...
158
  func (l *Logger) CombineHTTPLogs(in string, out string) {
372beaf62   Marko Tikvić   refactored if sta...
159
160
161
  	if l.outputFile == nil {
  		return
  	}
df74f4a7e   Marko Tikvić   new filename format
162

372beaf62   Marko Tikvić   refactored if sta...
163
164
  	l.mu.Lock()
  	defer l.mu.Unlock()
093191eb2   Marko Tikvić   much cleaner, muc...
165
  	msg := in + out
372beaf62   Marko Tikvić   refactored if sta...
166
167
  	if l.shouldSplit(len(msg)) {
  		l.split()
98708cdaf   Marko Tikvić   new version, does...
168
  	}
372beaf62   Marko Tikvić   refactored if sta...
169
  	l.outputFile.WriteString(msg)
98708cdaf   Marko Tikvić   new version, does...
170
  }
92485819d   Marko Tikvić   lint
171
  // Close ...
df74f4a7e   Marko Tikvić   new filename format
172
  func (l *Logger) Close() {
372beaf62   Marko Tikvić   refactored if sta...
173
174
175
176
177
178
  	if l.outputFile == nil {
  		return
  	}
  
  	err := l.outputFile.Close()
  	if err != nil {
b45f88e17   Marko Tikvić   more readable dat...
179
180
  		fmt.Fprintf(os.Stderr, "gologger: couldn't close event log file: %s
  ", err.Error())
a99c98307   Marko Tikvić   first commit
181
  	}
a99c98307   Marko Tikvić   first commit
182
  }
98cf2ceeb   Marko Tikvić   new interaface; a...
183
  func (l *Logger) split() {
372beaf62   Marko Tikvić   refactored if sta...
184
185
186
  	if l.outputFile == nil {
  		return
  	}
98cf2ceeb   Marko Tikvić   new interaface; a...
187
188
189
  	// close old file
  	err := l.outputFile.Close()
  	if err != nil {
b45f88e17   Marko Tikvić   more readable dat...
190
191
  		fmt.Fprintf(os.Stderr, "gologger: split: couldn't close event file
  ")
98cf2ceeb   Marko Tikvić   new interaface; a...
192
193
  		return
  	}
df74f4a7e   Marko Tikvić   new filename format
194
195
  
  	l.splitCount++
98cf2ceeb   Marko Tikvić   new interaface; a...
196
197
  	// open new file
  	var errnew error
3e936a3c2   Marko Tikvić   output file name ...
198
  	path := filepath.Join(logDirName, l.outputFileName+fmt.Sprintf("(%d)", l.splitCount)+".txt")
98cf2ceeb   Marko Tikvić   new interaface; a...
199
  	l.outputFile, errnew = os.Create(path)
a99c98307   Marko Tikvić   first commit
200

98cf2ceeb   Marko Tikvić   new interaface; a...
201
  	if errnew != nil {
b45f88e17   Marko Tikvić   more readable dat...
202
203
  		fmt.Fprintf(os.Stderr, "gologger: couldn't create new event log file: %s
  ", err.Error())
a99c98307   Marko Tikvić   first commit
204
205
  	}
  }
98cf2ceeb   Marko Tikvić   new interaface; a...
206
207
208
  func (l *Logger) shouldSplit(nextEntrySize int) bool {
  	stats, _ := l.outputFile.Stat()
  	return int64(nextEntrySize) >= (l.maxFileSize - stats.Size())
a99c98307   Marko Tikvić   first commit
209
  }