-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
103 lines (96 loc) · 1.96 KB
/
log.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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"time"
)
var logDir string = "./"
var logFile *os.File
func init() {
switch runtime.GOOS {
case "windows":
dir := "C:\\ProgramData\\assemblix"
err := os.Mkdir(dir, 0o664)
if err != nil {
logWarning(err)
logDir = "./"
break
}
logDir = dir
case "linux", "darwin":
dir := "/var/log/assemblix"
err := os.Mkdir(dir, 0o664)
if err != nil {
logWarning(err)
logDir = "./"
break
}
logDir = dir
default:
logDir = "./"
}
var err error
for {
logFile, err = os.OpenFile(filepath.Join(logDir, "server.log"), os.O_APPEND|os.O_CREATE, 0o644)
if err != nil {
logWarning(err)
logDir = "./"
continue
}
break
}
}
func logError(err error) {
var parsed = parseFormat("ERROR", err)
if logFile == nil {
fmt.Println(parsed)
return
}
fmt.Fprintln(logFile, parsed)
}
func logWarning(err error) {
var parsed = parseFormat("WARNING", err)
if logFile == nil {
fmt.Println(parsed)
return
}
fmt.Fprintln(logFile, parsed)
}
func logInfo(err error) {
var parsed = parseFormat("INFO", err)
if logFile == nil {
fmt.Println(parsed)
return
}
fmt.Fprintln(logFile, parsed)
}
func parseFormat(logType string, err error) string {
result := regexp.MustCompile(`(\\)?date`).ReplaceAllStringFunc(logFormat, func(match string) string {
if match[0] == '\\' {
return match[1:]
}
return time.Now().Format("2006-01-02")
})
result = regexp.MustCompile(`(\\)?time`).ReplaceAllStringFunc(result, func(match string) string {
if match[0] == '\\' {
return match[1:]
}
return time.Now().Format("15:04:05")
})
result = regexp.MustCompile(`(\\)?type`).ReplaceAllStringFunc(result, func(match string) string {
if match[0] == '\\' {
return match[1:]
}
return logType
})
result = regexp.MustCompile(`(\\)?error`).ReplaceAllStringFunc(result, func(match string) string {
if match[0] == '\\' {
return match[1:]
}
return err.Error()
})
return result
}