From fad8686a73212698dc7e8d77510d22fe0878486a Mon Sep 17 00:00:00 2001 From: Yun <995116474@qq.com> Date: Wed, 15 Jan 2025 15:29:45 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=81=E8=AE=B8=E9=85=8D=E7=BD=AEjson?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E8=BD=AC=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example/main.go | 13 +++++++------ format.go | 16 ++++++++++++++-- options.go | 8 ++++++++ 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/example/main.go b/example/main.go index 1d7e6d7..c6a7ab3 100644 --- a/example/main.go +++ b/example/main.go @@ -14,15 +14,16 @@ func main() { loggerx.SetToConsole(), // loggerx.SetTimeZone(time.UTC), loggerx.SetTimeZone(time.FixedZone("CST", 8*3600)), + loggerx.SetEscapeHTML(false), ) - log.WriteAsync().Info(ctx, "哈哈哈2异步") - log.Info(ctx, "哈哈哈2") - log.Info(ctx, "哈哈哈2") - log.Info(ctx, "哈哈哈2") - log.Info(ctx, "哈哈哈2") - log.Info(ctx, "哈哈哈2") + log.WriteAsync().Info(ctx, "{ \"a\": 1, \"b\": 2 }") log.Info(ctx, "哈哈哈2") log.Info(ctx, "哈哈哈2") + log.Info(ctx, "哈哈哈2\r") + log.Info(ctx, "哈哈哈2\r\n") + log.Info(ctx, "哈哈哈2") + log.Info(ctx, "哈哈哈2<") + log.Info(ctx, "哈哈哈2>") for i := 0; i < 100; i++ { log.WriteAsync().Infof(ctx, "异步 %d", i) diff --git a/format.go b/format.go index 1747b85..2894c2d 100644 --- a/format.go +++ b/format.go @@ -1,6 +1,7 @@ package loggerx import ( + "bytes" "context" "encoding/json" "fmt" @@ -32,7 +33,7 @@ func (l *Logger) logger(ctx context.Context, event string, v ...any) { // writeStr := "[" + event + "]" + nowTime + " " + file + ":" + fmt.Sprintf("%d", line) + " " + funcName + " gid:" + getGID() + " " + traceId + " @data@: " + string(by) + "\n\n" - for idx,val := range v { + for idx, val := range v { if _, ok := val.(error); ok { v[idx] = fmt.Sprintf("%+v", val) } @@ -51,7 +52,18 @@ func (l *Logger) logger(ctx context.Context, event string, v ...any) { // fd.Stack = string(debug.Stack()) } - fdb, _ := json.Marshal(fd) + var fdb []byte + if l.option.escapeHTML { + fdb, _ = json.Marshal(fd) + } else { + // 非转义 + var buf bytes.Buffer + encoder := json.NewEncoder(&buf) + encoder.SetEscapeHTML(false) + encoder.Encode(fd) + fdb = buf.Bytes() + } + fdb = bytes.TrimRight(fdb, "\n") ff := []byte("\n[" + event + "]") fdb = append(ff, fdb...) diff --git a/options.go b/options.go index ce15e2d..b927370 100644 --- a/options.go +++ b/options.go @@ -21,6 +21,7 @@ type loggerOption struct { fileSplit FileSplit // 文件切割规则 sizeSplit int // 根据文件大小切割 timeZone *time.Location // 时区 + escapeHTML bool } type writeType uint8 @@ -44,6 +45,7 @@ func defaultOptions() loggerOption { days: 7, fileSplit: FileSplitTimeE, timeZone: time.Local, + escapeHTML: true, } } @@ -176,3 +178,9 @@ func SetSizeSplit(m int) Option { o.sizeSplit = m } } + +func SetEscapeHTML(b bool) Option { + return func(o *loggerOption) { + o.escapeHTML = b + } +}