Skip to content

Commit 937444f

Browse files
committed
update: 去掉 github.com/lestrrat-go/file-rotatelogs 库的依赖, 实现zap.String("business", "xx")自定义业务日志数据路径, 输出文件路径为./global.GVA_CONFIG.Zap.Director/2006-01-02/xx/level(debug, info, warn, error, dpanic, panic, fatal).log
1 parent 3faf085 commit 937444f

File tree

5 files changed

+102
-30
lines changed

5 files changed

+102
-30
lines changed

server/core/internal/cutter.go

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package internal
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"regexp"
7+
"strings"
8+
"sync"
9+
"time"
10+
)
11+
12+
type Cutter struct {
13+
level string // 日志级别(debug, info, warn, error, dpanic, panic, fatal)
14+
format string // 时间格式(2006-01-02)
15+
Director string // 日志文件夹
16+
file *os.File // 文件句柄
17+
mutex *sync.RWMutex // 读写锁
18+
}
19+
20+
type CutterOption func(*Cutter)
21+
22+
// WithCutterFormat 设置时间格式
23+
func WithCutterFormat(format string) CutterOption {
24+
return func(c *Cutter) {
25+
c.format = format
26+
}
27+
}
28+
29+
func NewCutter(director string, level string, options ...CutterOption) *Cutter {
30+
rotate := &Cutter{
31+
level: level,
32+
Director: director,
33+
mutex: new(sync.RWMutex),
34+
}
35+
for i := 0; i < len(options); i++ {
36+
options[i](rotate)
37+
}
38+
return rotate
39+
}
40+
41+
// Write satisfies the io.Writer interface. It writes to the
42+
// appropriate file handle that is currently being used.
43+
// If we have reached rotation time, the target file gets
44+
// automatically rotated, and also purged if necessary.
45+
func (c *Cutter) Write(bytes []byte) (n int, err error) {
46+
c.mutex.Lock()
47+
defer func() {
48+
if c.file != nil {
49+
_ = c.file.Close()
50+
c.file = nil
51+
}
52+
c.mutex.Unlock()
53+
}()
54+
var business string
55+
if strings.Contains(string(bytes), "business") {
56+
var compile *regexp.Regexp
57+
compile, err = regexp.Compile(`{"business": "([^,]+)"}`)
58+
if err != nil {
59+
return 0, err
60+
}
61+
if compile.Match(bytes) {
62+
finds := compile.FindSubmatch(bytes)
63+
business = string(finds[len(finds)-1])
64+
bytes = compile.ReplaceAll(bytes, []byte(""))
65+
}
66+
compile, err = regexp.Compile(`"business": "([^,]+)"`)
67+
if err != nil {
68+
return 0, err
69+
}
70+
if compile.Match(bytes) {
71+
finds := compile.FindSubmatch(bytes)
72+
business = string(finds[len(finds)-1])
73+
bytes = compile.ReplaceAll(bytes, []byte(""))
74+
}
75+
}
76+
format := time.Now().Format(c.format)
77+
formats := make([]string, 0, 4)
78+
formats = append(formats, c.Director)
79+
if format != "" {
80+
formats = append(formats, format)
81+
}
82+
if business != "" {
83+
formats = append(formats, business)
84+
}
85+
formats = append(formats, c.level+".log")
86+
filename := filepath.Join(formats...)
87+
dirname := filepath.Dir(filename)
88+
err = os.MkdirAll(dirname, 0755)
89+
if err != nil {
90+
return 0, err
91+
}
92+
c.file, err = os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
93+
if err != nil {
94+
return 0, err
95+
}
96+
return c.file.Write(bytes)
97+
}

server/core/internal/file_rotatelogs.go

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,8 @@ package internal
22

33
import (
44
"github.com/flipped-aurora/gin-vue-admin/server/global"
5-
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
65
"go.uber.org/zap/zapcore"
76
"os"
8-
"path"
9-
"time"
107
)
118

129
var FileRotatelogs = new(fileRotatelogs)
@@ -15,15 +12,10 @@ type fileRotatelogs struct{}
1512

1613
// GetWriteSyncer 获取 zapcore.WriteSyncer
1714
// Author [SliverHorn](https://github.com/SliverHorn)
18-
func (r *fileRotatelogs) GetWriteSyncer(level string) (zapcore.WriteSyncer, error) {
19-
fileWriter, err := rotatelogs.New(
20-
path.Join(global.GVA_CONFIG.Zap.Director, "%Y-%m-%d", level+".log"),
21-
rotatelogs.WithClock(rotatelogs.Local),
22-
rotatelogs.WithMaxAge(time.Duration(global.GVA_CONFIG.Zap.MaxAge)*24*time.Hour), // 日志留存时间
23-
rotatelogs.WithRotationTime(time.Hour*24),
24-
)
15+
func (r *fileRotatelogs) GetWriteSyncer(level string) zapcore.WriteSyncer {
16+
fileWriter := NewCutter(global.GVA_CONFIG.Zap.Director, level, WithCutterFormat("2006-01-02"))
2517
if global.GVA_CONFIG.Zap.LogInConsole {
26-
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err
18+
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter))
2719
}
28-
return zapcore.AddSync(fileWriter), err
20+
return zapcore.AddSync(fileWriter)
2921
}

server/core/internal/zap.go

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package internal
22

33
import (
4-
"fmt"
54
"github.com/flipped-aurora/gin-vue-admin/server/global"
65
"go.uber.org/zap"
76
"go.uber.org/zap/zapcore"
@@ -42,12 +41,7 @@ func (z *_zap) GetEncoderConfig() zapcore.EncoderConfig {
4241
// GetEncoderCore 获取Encoder的 zapcore.Core
4342
// Author [SliverHorn](https://github.com/SliverHorn)
4443
func (z *_zap) GetEncoderCore(l zapcore.Level, level zap.LevelEnablerFunc) zapcore.Core {
45-
writer, err := FileRotatelogs.GetWriteSyncer(l.String()) // 使用file-rotatelogs进行日志分割
46-
if err != nil {
47-
fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
48-
return nil
49-
}
50-
44+
writer := FileRotatelogs.GetWriteSyncer(l.String()) // 日志分割
5145
return zapcore.NewCore(z.GetEncoder(), writer, level)
5246
}
5347

server/go.mod

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ require (
1818
github.com/gookit/color v1.5.4
1919
github.com/huaweicloud/huaweicloud-sdk-go-obs v3.21.8+incompatible
2020
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84
21-
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
2221
github.com/mojocn/base64Captcha v1.3.5
2322
github.com/otiai10/copy v1.7.0
2423
github.com/pkg/errors v0.9.1
@@ -80,13 +79,11 @@ require (
8079
github.com/jinzhu/inflection v1.0.0 // indirect
8180
github.com/jinzhu/now v1.1.5 // indirect
8281
github.com/jmespath/go-jmespath v0.4.0 // indirect
83-
github.com/jonboulle/clockwork v0.4.0 // indirect
8482
github.com/josharian/intern v1.0.0 // indirect
8583
github.com/json-iterator/go v1.1.12 // indirect
8684
github.com/klauspost/compress v1.13.6 // indirect
8785
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
8886
github.com/leodido/go-urn v1.2.4 // indirect
89-
github.com/lestrrat-go/strftime v1.0.6 // indirect
9087
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
9188
github.com/magiconair/properties v1.8.7 // indirect
9289
github.com/mailru/easyjson v0.7.7 // indirect

server/go.sum

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -268,8 +268,6 @@ github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9Y
268268
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
269269
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
270270
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
271-
github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4=
272-
github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc=
273271
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84 h1:pS0A6cr4aHYZnYwC7Uw+rwgb39+nzkm2QhwZ+S6Gn5I=
274272
github.com/jordan-wright/email v0.0.0-20200824153738-3f5bafa1cd84/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
275273
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
@@ -298,12 +296,6 @@ github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+
298296
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
299297
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
300298
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
301-
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8=
302-
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is=
303-
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4=
304-
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA=
305-
github.com/lestrrat-go/strftime v1.0.6 h1:CFGsDEt1pOpFNU+TJB0nhz9jl+K0hZSLE205AhTIGQQ=
306-
github.com/lestrrat-go/strftime v1.0.6/go.mod h1:f7jQKgV5nnJpYgdEasS+/y7EsTb8ykN2z68n3TtcTaw=
307299
github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8=
308300
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
309301
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=

0 commit comments

Comments
 (0)