Skip to content

Commit a39535e

Browse files
author
myxy99
committed
log
1 parent da44eaf commit a39535e

File tree

4 files changed

+113
-63
lines changed

4 files changed

+113
-63
lines changed

xlog/api.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,30 @@ package xlog
22

33
import (
44
"go.uber.org/zap"
5+
"sync"
56
)
67

78
func logger() *Logger {
8-
if defaultLogger == nil {
9+
one.Do(func() {
910
cfg := StdConfig()
1011
defaultLogger = cfg.Build()
11-
}
12+
})
1213
return defaultLogger
1314
}
1415

1516
func DefaultLogger() *Logger {
1617
return logger()
1718
}
1819

19-
func SetDefaultLogger(o *options) {
20-
defaultLogger = o.Build()
20+
func SetDefaultLogger(l *Logger) {
21+
defaultLogger = l
2122
return
2223
}
2324

24-
var defaultLogger *Logger
25+
var (
26+
defaultLogger *Logger
27+
one = sync.Once{}
28+
)
2529

2630
// Auto ...
2731
func Auto(err error) Func {

xlog/field.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ func FieldCode(value int32) Field {
3838
return Int32("code", value)
3939
}
4040

41+
// FieldTid 设置链路id
42+
func FieldTid(value string) Field {
43+
return String("tid", value)
44+
}
45+
4146
func FieldSize(value int32) Field {
4247
return Int32("size", value)
4348
}
@@ -91,10 +96,6 @@ func FieldMethod(value string) Field {
9196
return String("method", value)
9297
}
9398

94-
// FieldEvent ...
95-
func FieldEvent(value string) Field {
96-
return String("event", value)
97-
}
9899

99100
func FieldIp(value string) Field {
100101
return String("ip", value)

xlog/log.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,20 +59,18 @@ func newLogger(o *options) *Logger {
5959
if o.AddCaller {
6060
zapOptions = append(zapOptions, zap.AddCaller(), zap.AddCallerSkip(o.CallerSkip))
6161
}
62-
if len(o.Fields) > 0 {
63-
zapOptions = append(zapOptions, zap.Fields(o.Fields...))
62+
if len(o.fields) > 0 {
63+
zapOptions = append(zapOptions, zap.Fields(o.fields...))
6464
}
6565

66-
var ws zapcore.WriteSyncer
66+
var ws = zapcore.AddSync(newRotate(o))
6767
if o.Debug {
68-
ws = os.Stdout
69-
} else {
70-
ws = zapcore.AddSync(newRotate(o))
68+
ws = zap.CombineWriteSyncers(os.Stdout, ws)
7169
}
7270

7371
if o.Async {
7472
var closeFunc CloseFunc
75-
ws, closeFunc = Buffer(ws, defaultBufferSize, defaultFlushInterval)
73+
ws, closeFunc = Buffer(ws, o.FlushBufferSize, o.FlushBufferInterval)
7674

7775
xdefer.Register(closeFunc)
7876
}
@@ -82,8 +80,8 @@ func newLogger(o *options) *Logger {
8280
panic(err)
8381
}
8482

85-
encoderConfig := *o.EncoderConfig
86-
core := o.Core
83+
encoderConfig := *o.encoderConfig
84+
core := o.core
8785
if core == nil {
8886
core = zapcore.NewCore(
8987
func() zapcore.Encoder {

xlog/options.go

Lines changed: 92 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,24 @@ import (
1212
)
1313

1414
type options struct {
15-
// Dir 日志输出目录
16-
Dir string `mapStructure:"dir"`
17-
// Name 日志文件名称
18-
Name string `mapStructure:"name"`
19-
// Level 日志初始等级
20-
Level string `mapStructure:"level"`
21-
// 日志初始化字段
22-
Fields []zap.Field `mapStructure:"fields"`
23-
// 是否添加调用者信息
24-
AddCaller bool `mapStructure:"add_caller"`
25-
// 日志前缀
26-
Prefix string `mapStructure:"prefix"`
27-
// 日志输出文件最大长度,超过改值则截断
28-
MaxSize int `mapStructure:"max_size"`
29-
MaxAge int `mapStructure:"max_age"`
30-
MaxBackup int `mapStructure:"max_backup"`
31-
// 日志磁盘刷盘间隔
32-
Interval time.Duration `mapStructure:"interval"`
33-
CallerSkip int `mapStructure:"caller_skip"`
34-
Async bool `mapStructure:"async"`
35-
Queue bool `mapStructure:"queue"`
36-
QueueSleep time.Duration `mapStructure:"queue_sleep"`
37-
Core zapcore.Core `mapStructure:"core"`
38-
Debug bool `mapStructure:"debug"`
39-
EncoderConfig *zapcore.EncoderConfig `mapStructure:"encoder_config"`
40-
ConfigKey string `mapStructure:"config_key"`
15+
Dir string `mapStructure:"dir"` //Dir 日志输出目录
16+
Name string `mapStructure:"name"` //Name 日志文件名称
17+
Level string `mapStructure:"level"` //Level 日志初始等级
18+
AddCaller bool `mapStructure:"add_caller"` //是否添加调用者信息
19+
MaxSize int `mapStructure:"max_size"` //日志输出文件最大长度,超过改值则截断,默认500M
20+
MaxAge int `mapStructure:"max_age"` //日志存储最大时间,默认最大保存天数为7天
21+
MaxBackup int `mapStructure:"max_backup"` //日志存储最大数量,默认最大保存文件个数为10个
22+
Interval time.Duration `mapStructure:"interval"` //日志轮转时间,默认1天
23+
CallerSkip int `mapStructure:"caller_skip"` //调用堆栈
24+
Async bool `mapStructure:"async"` //是否异步,默认异步
25+
ConfigKey string `mapStructure:"config_key"` //config key
26+
Debug bool `mapStructure:"debug"` //debug
27+
FlushBufferSize int `mapStructure:"flush_buffer_size"` //缓冲大小,默认256 * 1024B
28+
FlushBufferInterval time.Duration `mapStructure:"flush_buffer_interval"` //缓冲时间,默认30秒
29+
30+
fields []zap.Field `mapStructure:"fields"` //日志初始化字段
31+
encoderConfig *zapcore.EncoderConfig `mapStructure:"encoder_config"`
32+
core zapcore.Core `mapStructure:"core"`
4133
}
4234

4335
// Filename ...
@@ -70,32 +62,39 @@ func StdConfig(name ...string) *options {
7062
// DefaultConfig ...
7163
func defaultConfig() *options {
7264
return &options{
73-
Name: "log.log",
74-
Dir: ".",
75-
Level: "",
76-
MaxSize: 500, // 500M
77-
MaxAge: 1, // 1 day
78-
MaxBackup: 10, // 10 backup
79-
Interval: 24 * time.Hour,
80-
CallerSkip: 2,
81-
AddCaller: true,
82-
Debug: true,
83-
Async: false,
84-
Queue: false,
85-
QueueSleep: 100 * time.Millisecond,
86-
EncoderConfig: DefaultZapConfig(),
65+
Dir: ".",
66+
Name: "log.log",
67+
Level: "info",
68+
AddCaller: true,
69+
MaxSize: 500, // 500M
70+
MaxAge: 1, // 1 day
71+
MaxBackup: 10, // 10 backup
72+
Interval: 24 * time.Hour,
73+
CallerSkip: 2,
74+
Async: false,
75+
ConfigKey: "xlog",
76+
Debug: true,
77+
FlushBufferSize: defaultBufferSize,
78+
FlushBufferInterval: defaultFlushInterval,
79+
fields: nil,
80+
encoderConfig: DefaultZapConfig(),
81+
core: nil,
8782
}
8883
}
8984

9085
// Build ...
91-
func (o options) Build() *Logger {
92-
if o.EncoderConfig == nil {
93-
o.EncoderConfig = DefaultZapConfig()
86+
func (o *options) Build(options ...Option) *Logger {
87+
for _, option := range options {
88+
option(o)
89+
}
90+
if o.encoderConfig == nil {
91+
o.encoderConfig = DefaultZapConfig()
9492
}
9593
if o.Debug {
96-
o.EncoderConfig.EncodeLevel = DebugEncodeLevel
94+
o.encoderConfig.EncodeLevel = DebugEncodeLevel
95+
o.encoderConfig.EncodeTime = timeDebugEncoder
9796
}
98-
logger := newLogger(&o)
97+
logger := newLogger(o)
9998
if o.ConfigKey != "" {
10099
logger.AutoLevel(o.ConfigKey + ".level")
101100
}
@@ -137,3 +136,51 @@ func DebugEncodeLevel(lv zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
137136
func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
138137
enc.AppendInt64(t.Unix())
139138
}
139+
140+
func timeDebugEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
141+
enc.AppendString(t.Format("2006-01-02 15:04:05"))
142+
}
143+
144+
// Option 可选项
145+
type Option func(c *options)
146+
147+
// WithFileName 设置文件名
148+
func WithFileName(name string) Option {
149+
return func(c *options) {
150+
c.Name = name
151+
}
152+
}
153+
154+
// WithDebug 设置在命令行显示
155+
func WithDebug(debug bool) Option {
156+
return func(c *options) {
157+
c.Debug = debug
158+
}
159+
}
160+
161+
// WithLevel 设置级别
162+
func WithLevel(level string) Option {
163+
return func(c *options) {
164+
c.Level = level
165+
}
166+
}
167+
168+
// WithEnableAsync 是否异步执行,默认异步
169+
func WithEnableAsync(enableAsync bool) Option {
170+
return func(c *options) {
171+
c.Async = enableAsync
172+
}
173+
}
174+
175+
// WithEnableAddCaller 是否添加行号,默认不添加行号
176+
func WithEnableAddCaller(enableAddCaller bool) Option {
177+
return func(c *options) {
178+
c.AddCaller = enableAddCaller
179+
}
180+
}
181+
182+
func WithFields(f []Field) Option {
183+
return func(c *options) {
184+
c.fields = f
185+
}
186+
}

0 commit comments

Comments
 (0)