-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.go
97 lines (86 loc) · 1.73 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
// logger
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/kardianos/osext"
)
type statusWriter struct {
http.ResponseWriter
status int
length int
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
w.length = len(b)
return w.ResponseWriter.Write(b)
}
var logChan = make(chan string, 10000)
var basePath string
func init() {
go func() {
const fmtFileName = "${app_path}/log/ex${date}.log"
var (
lastLogging = time.Time{}
logFile *os.File
err error
str string
)
defer func() {
if logFile != nil {
logFile.Close()
}
}()
basePath = ""
exeName, err := osext.Executable()
if err == nil {
exeName, err = filepath.Abs(exeName)
if err == nil {
basePath = filepath.Dir(exeName)
}
}
for {
select {
case str = <-logChan:
{
if lastLogging.Format("2006_01_02") != time.Now().Format("2006_01_02") {
if logFile != nil {
logFile.Close()
}
fileName := os.Expand(fmtFileName, func(key string) string {
switch strings.ToUpper(key) {
case "APP_PATH":
return basePath
case "DATE":
return time.Now().Format("2006_01_02")
default:
return ""
}
})
dir, _ := filepath.Split(fileName)
os.MkdirAll(dir, os.ModeDir)
logFile, err = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalln(err)
}
}
lastLogging = time.Now()
logFile.WriteString(str)
}
}
}
}()
}
func writeToLog(msg string) {
logChan <- msg
}