-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
121 lines (96 loc) · 2.51 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
package gouse
import (
"log"
"os"
"time"
)
func WriteLogDefault(logID, logMessage, output string) {
file, err := os.OpenFile(output, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
log.Printf("Failed to open log file: %v", err)
}
if err := (os.Chmod(output, 0600)); err != nil {
log.Printf("Error setting chmod log file handle permissions: %v", err)
}
defer func() {
if err := file.Close(); err != nil {
log.Printf("Failed to close log file: %v", err)
}
}()
// Create a new logger that writes to the log file
logger := log.New(file, logID, log.Ldate|log.Ltime|log.Lshortfile)
// Write some log messages
logger.Println(logMessage)
}
type ILog struct {
Prefix string
Message string
Output string
}
func WriteLog(prefix, msg, filePath string, err ...interface{}) {
logParam := &ILog{
Prefix: prefix,
Message: "",
Output: filePath,
}
logId := RandStr(8)
if len(err) > 0 {
errStr := DetectError(err)
logParam.Message = Sprintf("Message: %s - ID: %s - Error: %s - Date: \n", msg, logId, errStr)
} else {
logParam.Message = Sprintf("Message: %s - ID: %s - Date: \n", msg, logId)
}
WriteLogDefault(logParam.Output, Sprintf("%s %s", logParam.Prefix, logParam.Message), logParam.Output)
}
func WriteErrorLog(msg string, err interface{}) {
WriteLog(ERROR_LOG_PREFIX, msg, ERROR_LOG_PATH, err)
}
func WriteInfoLog(msg string) {
WriteLog(INFO_LOG_PREFIX, msg, INFO_LOG_PATH)
}
func WriteAccessLog(msg string) {
WriteLog(ACCESS_LOG_PREFIX, msg, ACCESS_LOG_PATH)
}
func truncateLog(file *os.File) error {
err := file.Truncate(0)
if err != nil {
return err
}
_, err = file.Seek(0, 0)
if err != nil {
return err
}
return nil
}
func RotateLog(output string, maxFileSize ...int64) {
maxSize := int64(1 * 1024 * 1024) // 1MB
if len(maxFileSize) > 0 {
maxSize = int64(maxFileSize[0])
}
logFile, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Printf("Error opening log file: %v", err)
}
if err := (os.Chmod(output, 0600)); err != nil {
log.Printf("Error setting chmod rotate log file permissions: %v", err)
}
defer func() {
if err := logFile.Close(); err != nil {
log.Print("Failed to close log file: ", err)
}
}()
log.SetOutput(logFile)
for {
info, err := logFile.Stat()
if err != nil {
log.Printf("Error getting log file stats: %v", err)
}
if info.Size() >= maxSize {
err = truncateLog(logFile)
if err != nil {
log.Printf("Error truncating log file: %v", err)
}
}
time.Sleep(time.Minute)
}
}