允许配置json是否转义

This commit is contained in:
Yun
2025-01-15 15:29:45 +08:00
parent 33706c1072
commit fad8686a73
3 changed files with 29 additions and 8 deletions
+7 -6
View File
@@ -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<b>")
log.Info(ctx, "哈哈哈2<")
log.Info(ctx, "哈哈哈2>")
for i := 0; i < 100; i++ {
log.WriteAsync().Infof(ctx, "异步 %d", i)
+13 -1
View File
@@ -1,6 +1,7 @@
package loggerx
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -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...)
+8
View File
@@ -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
}
}