/
logging.go
314 lines (235 loc) · 5.43 KB
/
logging.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package common
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"os/exec"
)
const (
// DB level
LEVEL_PROLOG = iota
// LEVEL_DEBUG level
LEVEL_DEBUG
// LEVEL_INFO level
LEVEL_INFO
// LEVEL_ERROR level
LEVEL_WARN
// LEVEL_ERROR level
LEVEL_ERROR
// LEVEL_FATAL level
LEVEL_FATAL
)
type logEntry struct {
level int
txt string
}
var (
logLevel = LEVEL_INFO
logConsole *bool
logFilename *string
logFileSize *int
logLevelString *string
defaultLogFile string
logEntries chan logEntry
mutex sync.Mutex
wg sync.WaitGroup
logFile *os.File
)
func init() {
filename, err := os.Executable()
if err != nil {
filename = os.Args[0]
}
ext := filepath.Ext(filename)
if len(ext) > 0 {
filename = string(filename[:len(filename)-len(ext)])
}
filename += ".log"
path, err := os.Getwd()
if err == nil {
filename = filepath.Join(path, filepath.Base(filename))
}
defaultLogFile = filename
logConsole = flag.Bool("logconsole", true, "log to console")
logFilename = flag.String("logfile", "", fmt.Sprintf("filename to log logFile (use \".\" for %s)", defaultLogFile))
logFileSize = flag.Int("logfilesize", 10, "log logFile size in MB")
logLevelString = flag.String("loglevel", "info", "log level (debug,info,error,fatal)")
}
func initLog() {
mutex.Lock()
if logEntries == nil {
var err error
logEntries = make(chan logEntry, 100)
switch strings.ToLower(*logLevelString) {
case "debug":
logLevel = LEVEL_DEBUG
case "info":
logLevel = LEVEL_INFO
case "warn":
logLevel = LEVEL_WARN
case "error":
logLevel = LEVEL_ERROR
case "fatal":
logLevel = LEVEL_FATAL
default:
logLevel = LEVEL_INFO
}
if *logFilename == "." {
*logFilename = defaultLogFile
}
go func() {
timeout := time.Millisecond * 500
t := time.NewTimer(timeout)
loop:
for {
select {
case <-t.C:
t.Stop()
closeLogFile(false)
case entry, ok := <-logEntries:
if !ok {
break loop
}
mutex.Lock()
t.Stop()
entry.txt = strings.TrimRight(entry.txt, "\r\n")
if logFile == nil && len(*logFilename) != 0 {
b, _ := FileExists(*logFilename)
if b {
fi, _ := os.Stat(*logFilename)
if fi.Size() > (int64(*logFileSize) * 1024 * 1024) {
os.Remove(*logFilename)
}
}
logFile, err = os.OpenFile(*logFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
if err != nil {
Fatal(fmt.Errorf("cannot write to logFile %s: %v", *logFilename, err))
}
}
if entry.level != LEVEL_PROLOG && *logConsole {
fmt.Fprintf(os.Stderr, "%s\n", entry.txt)
}
if logFile != nil {
logFile.WriteString(fmt.Sprintf("%s\n", entry.txt))
}
mutex.Unlock()
t.Reset(timeout)
wg.Done()
}
}
closeLogFile(true)
}()
AddShutdownHook(func() error {
closeLogFile(true)
return nil
})
prolog(fmt.Sprintf(">>> START - %s %s", strings.ToUpper(app.Name), app.Version))
prolog(fmt.Sprintf("cmdline : %s", strings.Join(SurroundWith(os.Args, "\""), " ")))
}
mutex.Unlock()
}
func closeLogFile(isFinal bool) {
DebugFunc()
if isFinal {
prolog(fmt.Sprintf("<<< STOP - %s %s", strings.ToUpper(app.Name), app.Version))
}
wg.Wait()
mutex.Lock()
if isFinal {
close(logEntries)
logEntries = nil
}
if logFile != nil {
logFile.Close()
logFile = nil
}
mutex.Unlock()
}
func fmtLog(level string, pos int, txt string) string {
ri := RuntimeInfo(pos + 1)
return fmt.Sprintf("%s %-5s %-40.40s %s", time.Now().Format(DateTimeMilliMask), level, ri.String(false), Capitalize(txt))
}
// logFile prints out the information
func prolog(t string, arg ...interface{}) {
if len(arg) > 0 {
t = fmt.Sprintf(t, arg...)
}
log(LEVEL_PROLOG, fmtLog("FILE", 2, t))
}
// Debug prints out the information
func Debug(t string, arg ...interface{}) {
initLog()
if len(arg) > 0 {
t = fmt.Sprintf(t, arg...)
}
log(LEVEL_DEBUG, fmtLog("DEBUG", 2, t))
}
// Info prints out the information
func Info(t string, arg ...interface{}) {
initLog()
if len(arg) > 0 {
t = fmt.Sprintf(t, arg...)
}
log(LEVEL_INFO, fmtLog("INFO", 2, t))
}
// Warn prints out the information
func Warn(t string, arg ...interface{}) {
initLog()
if len(arg) > 0 {
t = fmt.Sprintf(t, arg...)
}
log(LEVEL_WARN, fmtLog("WARN", 2, t))
}
// Warn prints out the error
func WarnError(err error) {
initLog()
if err != nil {
log(LEVEL_WARN, fmtLog("DEBUG", 2, fmt.Sprintf("Error: %s", err.Error())))
}
}
// DebugFunc prints out the current executon func
func DebugFunc() {
initLog()
ri := RuntimeInfo(1)
log(LEVEL_DEBUG, fmtLog("DEBUG", 2, ri.Fn+"()"))
}
// Debug prints out the information
func DebugError(err error) {
initLog()
if err != nil {
log(LEVEL_DEBUG, fmtLog("DEBUG", 2, fmt.Sprintf("Error: %s", err.Error())))
}
}
// Error prints out the error
func Error(err error) {
initLog()
if err != nil {
log(LEVEL_ERROR, fmtLog("ERROR", 2, err.Error()))
}
}
// Fatal prints out the error
func Fatal(err error) {
initLog()
if err != nil {
log(LEVEL_FATAL, fmtLog("FATAL", 2, err.Error()))
panic(err)
}
}
func log(level int, txt string) {
if logEntries != nil && (level == LEVEL_PROLOG || level >= logLevel) {
wg.Add(1)
logEntries <- logEntry{level, txt}
}
}
func ToString(cmd exec.Cmd) string {
s := SurroundWith(cmd.Args, "\"")
return strings.Join(s, " ")
}
func IsDebugMode() bool {
initLog()
return logLevel == LEVEL_DEBUG
}