添加打印到控制台的方法&添加设置时区

This commit is contained in:
Yun
2024-06-20 23:59:13 +08:00
parent 791a08b77a
commit bcd576e400
3 changed files with 26 additions and 11 deletions
+1 -1
View File
@@ -26,7 +26,7 @@ func (l *Logger) logger(ctx context.Context, event string, v ...any) {
by, _ := json.Marshal(v) by, _ := json.Marshal(v)
nowTime := time.Now().Local().Format("2006-01-02 15:04:05.000000") nowTime := time.Now().In(l.option.timeZone).Format("2006-01-02 15:04:05.000000")
traceId, _ := ctx.Value(l.option.traceField).(string) traceId, _ := ctx.Value(l.option.traceField).(string)
+3 -1
View File
@@ -20,7 +20,9 @@ func TestLogger(t *testing.T) {
l := loggerx.NewLogger( l := loggerx.NewLogger(
context.Background(), context.Background(),
loggerx.SetErrorToInfo(), loggerx.SetErrorToInfo(),
loggerx.SetExtraDriver(b, Print{}), loggerx.SetToConsole(),
loggerx.SetTimeZone(time.UTC),
// loggerx.SetExtraDriver(b, Print{}),
loggerx.SetFileSplit(loggerx.FileSplitTimeA), loggerx.SetFileSplit(loggerx.FileSplitTimeA),
) )
+16 -3
View File
@@ -1,6 +1,10 @@
package loggerx package loggerx
import "io" import (
"io"
"os"
"time"
)
type loggerOption struct { type loggerOption struct {
prefix string // 日志前缀 prefix string // 日志前缀
@@ -14,6 +18,7 @@ type loggerOption struct {
drivers []io.Writer // 文件落盘驱动器 drivers []io.Writer // 文件落盘驱动器
fileSplit FileSplit // 文件切割规则 fileSplit FileSplit // 文件切割规则
sizeSplit int // 根据文件大小切割 sizeSplit int // 根据文件大小切割
timeZone *time.Location // 时区
} }
func defaultOptions() loggerOption { func defaultOptions() loggerOption {
@@ -25,6 +30,7 @@ func defaultOptions() loggerOption {
traceField: "trace_id", traceField: "trace_id",
days: 7, days: 7,
fileSplit: FileSplitTimeE, fileSplit: FileSplitTimeE,
timeZone: time.Local,
} }
} }
@@ -37,6 +43,13 @@ func SetTraceField(traceField string) Option {
} }
} }
// 打印到控制台
func SetToConsole() Option {
return func(o *loggerOption) {
o.drivers = append(o.drivers, os.Stdout)
}
}
// 错误日志是否写入info日志 // 错误日志是否写入info日志
func SetErrorToInfo() Option { func SetErrorToInfo() Option {
return func(o *loggerOption) { return func(o *loggerOption) {
@@ -89,9 +102,9 @@ func SetDays(days int) Option {
} }
// 设置时区 // 设置时区
func SetTimeZone() Option { func SetTimeZone(loc *time.Location) Option {
return func(o *loggerOption) { return func(o *loggerOption) {
// o.timeZone = timeZone o.timeZone = loc
} }
} }