-
Notifications
You must be signed in to change notification settings - Fork 0
/
zp.go
120 lines (108 loc) · 2.48 KB
/
zp.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
/*
* Copyright (c) 2000-2018, 达梦数据库有限公司.
* All rights reserved.
*/
package dm
import (
"os"
"strconv"
"strings"
"time"
"github.com/gotomicro/dmgo/util"
)
const (
MAX_FILE_SIZE = 100 * 1024 * 1024
FLUSH_SIZE = 32 * 1024
)
type goRun interface {
doRun()
}
type logWriter struct {
flushQueue chan []byte
date string
logFile *os.File
flushFreq int
filePath string
filePrefix string
buffer *Dm_build_1498
}
func (lw *logWriter) doRun() {
defer func() {
lw.beforeExit()
lw.closeCurrentFile()
}()
i := 0
for {
var ibytes []byte
select {
case ibytes = <-lw.flushQueue:
if LogLevel != LOG_OFF {
if i == LogFlushQueueSize {
lw.doFlush(lw.buffer)
i = 0
} else {
lw.buffer.Dm_build_1524(ibytes, 0, len(ibytes))
i++
}
}
case <-time.After(time.Duration(LogFlushFreq) * time.Millisecond):
if LogLevel != LOG_OFF && lw.buffer.Dm_build_1503() > 0 {
lw.doFlush(lw.buffer)
i = 0
}
}
}
}
func (lw *logWriter) doFlush(buffer *Dm_build_1498) {
if lw.needCreateNewFile() {
lw.closeCurrentFile()
lw.logFile = lw.createNewFile()
}
buffer.Dm_build_1518(lw.logFile, buffer.Dm_build_1503())
}
func (lw *logWriter) closeCurrentFile() {
if lw.logFile != nil {
lw.logFile.Close()
lw.logFile = nil
}
}
func (lw *logWriter) createNewFile() *os.File {
lw.date = time.Now().Format("2006-01-02")
fileName := lw.filePrefix + "_" + lw.date + "_" + strconv.Itoa(time.Now().Nanosecond()) + ".log"
lw.filePath = LogDir
if len(lw.filePath) > 0 {
if _, err := os.Stat(lw.filePath); err != nil {
os.MkdirAll(lw.filePath, 0755)
}
if _, err := os.Stat(lw.filePath + fileName); err != nil {
logFile, err := os.Create(lw.filePath + fileName)
if err != nil {
panic(err)
}
return logFile
}
}
return nil
}
func (lw *logWriter) needCreateNewFile() bool {
now := time.Now().Format("2006-01-02")
fileInfo, err := lw.logFile.Stat()
return now != lw.date || err != nil || lw.logFile == nil || fileInfo.Size() > int64(MAX_FILE_SIZE)
}
func (lw *logWriter) beforeExit() {
close(lw.flushQueue)
var ibytes []byte
for ibytes = <-lw.flushQueue; ibytes != nil; ibytes = <-lw.flushQueue {
lw.buffer.Dm_build_1524(ibytes, 0, len(ibytes))
if lw.buffer.Dm_build_1503() >= LogBufferSize {
lw.doFlush(lw.buffer)
}
}
if lw.buffer.Dm_build_1503() > 0 {
lw.doFlush(lw.buffer)
}
}
func (lw *logWriter) WriteLine(msg string) {
var b = []byte(strings.TrimSpace(msg) + util.LINE_SEPARATOR)
lw.flushQueue <- b
}