-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
155 lines (147 loc) · 3.86 KB
/
logger.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
package helpers
import (
"time"
"os"
"sync"
"strings"
"strconv"
"fmt"
)
const (
logsFolder string = "logs"
endOfLog string = " --- END OF LOG ---\n"
)
var (
// Logger
logFile *os.File
logMux sync.Mutex
byteOn int64
entryOn int
logNum int
logInit bool
// Settings
maxLogFileSize int // Maximum log messages in a single log file
logPrio int // Minimum priority level to display. Priority level can be from 1 to 5
)
// InitLogger initializes the logging system and returns an error if anything goes wrong. The logger can only be used if
// it is successfully initialized.
func InitLogger(prio int, maxSize int) error {
if logInit {
return nil
}
if prio < 1 {
prio = 1
} else if prio > 5 {
prio = 5
}
if maxSize < 0 {
maxSize = 0
}
logPrio = prio
maxLogFileSize = maxSize
logMux.Lock()
logNum = 1
if logFile == nil {
now := time.Now()
var today string = strconv.Itoa(now.Day()) + "-" + strconv.Itoa(int(now.Month())) + "-" + strconv.Itoa(now.Year())
// Check if log folder exists
if _, err := os.Stat(logsFolder); os.IsNotExist(err) {
// Create logs folder
os.MkdirAll(logsFolder, os.ModePerm)
} else {
// Open log folder
df, err := os.Open(logsFolder)
if err != nil {
logMux.Unlock()
return err
}
// Get file list
files, flErr := df.Readdir(-1)
df.Close()
if flErr != nil {
logMux.Unlock()
return flErr
}
// Check for other log files from today's date and get logNum
for _, fileStats := range files {
fileNameSplit := strings.Split(fileStats.Name(), ".")
if fileNameSplit[0][:len(today)] == today {
// Found log file from today.
// Get logNum
ln, lnErr := strconv.Atoi(fileNameSplit[0][len(today) + 2:len(fileNameSplit[0]) - 1])
if lnErr != nil || len(fileNameSplit) < 2 || "." + fileNameSplit[1] != FileTypeLog {
continue
} else if logNum <= ln {
logNum = ln + 1
}
}
}
}
// Create new log file
var err error
if logFile, err = os.OpenFile(logsFolder + "/" + today + " (" + strconv.Itoa(logNum) + ")" + FileTypeLog, os.O_RDWR | os.O_CREATE, 0755); err != nil {
logMux.Unlock()
return err
}
// set byteOn and entryOn to 0
byteOn = 0
entryOn = 0
}
logMux.Unlock()
logInit = true
return nil
}
// Log appends the given string to the current log file. If the priority level is less than the minimum priority level
// threshold, the log will not be written.
func Log(in string, priority int) bool {
if !logInit || priority < logPrio {
return false
}
var now time.Time = time.Now()
logMux.Lock()
if logFile == nil {
return false
} else if maxLogFileSize > 0 && entryOn >= maxLogFileSize {
//
logFile.WriteAt([]byte(endOfLog), byteOn)
// Get today's date
var today string = strconv.Itoa(now.Day()) + "-" + strconv.Itoa(int(now.Month())) + "-" + strconv.Itoa(now.Year())
// Close current log file and increase logNum
logFile.Close()
logNum++
// Create new log file
var err error
if logFile, err = os.OpenFile(logsFolder + "/" + today + " (" + strconv.Itoa(logNum) + ")" + FileTypeLog, os.O_RDWR | os.O_CREATE, 0755); err != nil {
logMux.Unlock()
return false
}
// set byteOn and entryOn to 0
byteOn = 0
entryOn = 0
}
log := []byte("[" + now.Format("2006-01-02T15:04:05Z07:00") + "]: " + in + "\n")
// Append log to logFile
if _, wErr := logFile.WriteAt(log, byteOn); wErr != nil {
logMux.Unlock()
return false
}
byteOn += int64(len(log))
entryOn++
logMux.Unlock()
return true
}
func LogAndPrint(in string, priority int) bool {
if !Log(in, priority) {
return false
}
fmt.Println("[GopherDB Logger @ " + time.Now().Format("2006-01-02T15:04:05Z07:00") + "]: " + in)
return true
}
// CloseLogger closes the logger. Any subsequent logs will only be output to the console.
func CloseLogger() {
logMux.Lock()
logFile.WriteAt([]byte(endOfLog), byteOn)
logFile.Close()
logFile = nil
logMux.Unlock()
}