Files
loggerx/format.go
T

89 lines
2.0 KiB
Go
Raw Normal View History

2024-01-22 18:05:51 +08:00
package loggerx
import (
2025-01-15 15:29:45 +08:00
"bytes"
2024-01-22 18:05:51 +08:00
"context"
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"strings"
"time"
)
2024-01-23 00:12:08 +08:00
func (l *Logger) logger(ctx context.Context, event string, v ...any) {
2024-01-22 18:05:51 +08:00
pc, file, line, _ := runtime.Caller(2)
// fmt.Println("runtime.Caller", pc, file, line, ok)
2024-01-23 00:12:08 +08:00
basePath, _ := filepath.Abs("./")
basePath = strings.ReplaceAll(basePath, "\\", "/")
// fmt.Println("basePath", basePath)
file = strings.TrimPrefix(file, basePath)
2024-01-22 18:05:51 +08:00
funcName := runtime.FuncForPC(pc).Name()
funcName = filepath.Ext(funcName)
funcName = strings.TrimPrefix(funcName, ".")
2024-06-27 21:06:47 +08:00
// by, _ := json.Marshal(v)
2024-01-22 18:05:51 +08:00
nowTime := time.Now().In(l.option.timeZone).Format("2006-01-02 15:04:05.000000")
2024-01-23 00:12:08 +08:00
traceId, _ := ctx.Value(l.option.traceField).(string)
2024-01-22 18:05:51 +08:00
2024-02-03 01:57:56 +08:00
// writeStr := "[" + event + "]" + nowTime + " " + file + ":" + fmt.Sprintf("%d", line) + " " + funcName + " gid:" + getGID() + " " + traceId + " @data@: " + string(by) + "\n\n"
2025-01-15 15:29:45 +08:00
for idx, val := range v {
2024-07-26 17:52:32 +08:00
if _, ok := val.(error); ok {
v[idx] = fmt.Sprintf("%+v", val)
}
}
2024-02-03 01:57:56 +08:00
fd := FormatData{
Time: nowTime,
File: file + ":" + fmt.Sprintf("%d", line),
Func: funcName,
Gid: getGID(),
2024-06-27 21:06:47 +08:00
Content: v,
2024-02-03 01:57:56 +08:00
TraceId: traceId,
}
2024-04-18 12:02:44 +08:00
if event == "error" {
2024-04-19 10:49:30 +08:00
// fd.Stack = string(debug.Stack())
2024-04-18 12:02:44 +08:00
}
2025-01-15 15:29:45 +08:00
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")
2024-01-22 18:05:51 +08:00
2024-02-03 02:07:49 +08:00
ff := []byte("\n[" + event + "]")
fdb = append(ff, fdb...)
2024-02-03 01:57:56 +08:00
l.write(event, fdb)
2024-01-22 18:05:51 +08:00
2024-01-23 00:12:08 +08:00
if l.option.errorToInfo && event == "error" {
2024-02-03 01:57:56 +08:00
l.write("info", fdb)
2024-01-23 00:12:08 +08:00
}
2024-01-22 18:05:51 +08:00
// log.Println("" + string(by))
}
2024-02-03 01:57:56 +08:00
type FormatData struct {
2024-06-27 21:06:47 +08:00
Time string `json:"time,omitempty"`
File string `json:"file,omitempty"`
Func string `json:"func,omitempty"`
Gid string `json:"gid,omitempty"`
Content interface{} `json:"content,omitempty"`
TraceId string `json:"traceId,omitempty"`
Stack string `json:"stack,omitempty"`
2024-02-03 01:57:56 +08:00
}