update log

This commit is contained in:
白茶清欢 2023-09-01 19:18:39 +08:00
parent 8fd5b54a0c
commit bae9380210
2 changed files with 16 additions and 7 deletions

View File

@ -12,6 +12,7 @@ import (
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"log/slog"
"os"
"strings"
)
@ -25,7 +26,8 @@ const (
//
// Date : 17:59 2023/9/1
type FilterOption struct {
DebugModel bool // 调试模式
DebugModel bool // 调试模式
LogInstance *slog.Logger // 日志实例
}
// FilterDataRule 参数过滤规则
@ -49,6 +51,12 @@ func NewDataFilter(source string, filterRule []*FilterDataRule, filterOption *Fi
if nil == filterOption {
filterOption = &FilterOption{}
}
if filterOption.DebugModel && nil == filterOption.LogInstance {
filterOption.LogInstance = slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
slog.SetDefault(filterOption.LogInstance)
}
return &DataFilter{
source: source,
filterRule: filterRule,
@ -75,6 +83,7 @@ type DataFilter struct {
//
// Date : 2022/1/22 9:36 PM
func (df *DataFilter) Filter() (string, error) {
df.logPrint(logLevelInfo, "输入的原始数据", slog.String("source_data", df.source))
var (
err error
)
@ -128,22 +137,21 @@ func (df *DataFilter) setKV(rule *FilterDataRule) error {
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:00 2023/9/1
func (df *DataFilter) logPrint(level string, msg string, other ...interface{}) {
func (df *DataFilter) logPrint(level string, msg string, logAttr ...interface{}) {
if !df.filterOption.DebugModel {
// 未开启调试模式
return
}
switch level {
case logLevelFatal:
slog.Error(msg, other...)
slog.Error(msg, logAttr...)
case logLevelWarn:
slog.Warn(msg, other...)
slog.Warn(msg, logAttr...)
case logLevelInfo:
slog.Info(msg, other...)
slog.Info(msg, logAttr...)
case logLevelDebug:
slog.Debug(msg, other...)
slog.Debug(msg, logAttr...)
}
}
// 日志等级定义

View File

@ -37,6 +37,7 @@ func TestDataFilter_FilterNormalData(t *testing.T) {
{SourceKey: "none", MapKey: "none_default", DefaultValue: map[string]interface{}{"a": "a"}, WithDefault: true},
{SourceKey: "extra", MapKey: "extra_object", DefaultValue: map[string]interface{}{"a": "a"}, WithDefault: true},
},
filterOption: &FilterOption{DebugModel: true},
}
fmt.Println(df.Filter())
}