支持异步写入

This commit is contained in:
Yun
2024-11-22 20:08:25 +08:00
parent 7c70f805db
commit 33706c1072
5 changed files with 90 additions and 12 deletions
+23 -9
View File
@@ -21,11 +21,12 @@ import (
// 需要实现io.Writer接口
type Logger struct {
ctx context.Context
filePath *sync.Map // filePath
mu *sync.Mutex
option loggerOption
channel string
ctx context.Context
filePath *sync.Map // filePath
mu *sync.Mutex
option loggerOption
channel string
writeType writeType // 是否异步落盘,这里作用范围是本条,优先判断这里
}
type filePath struct {
@@ -45,10 +46,11 @@ func NewLogger(ctx context.Context, opts ...Option) *Logger {
}
l := &Logger{
ctx: ctx,
filePath: &sync.Map{},
mu: &sync.Mutex{},
option: opt,
ctx: ctx,
filePath: &sync.Map{},
mu: &sync.Mutex{},
option: opt,
writeType: writeTypeDefault,
}
log.SetOutput(l)
@@ -87,6 +89,18 @@ func (l *Logger) Channel(ch string) (r *Logger) {
return &rr
}
func (l *Logger) WriteAsync() (r *Logger) {
rr := *l
rr.writeType = writeTypeAsync
return &rr
}
func (l *Logger) WriteSync() (r *Logger) {
rr := *l
rr.writeType = writeTypeSync
return &rr
}
// 获取TraceField的字段
func (l *Logger) GetTraceField() string {
return l.option.traceField