Files
loggerx/format.go
T

72 lines
1.7 KiB
Go
Raw Normal View History

2024-01-22 18:05:51 +08:00
package loggerx
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"runtime"
2024-04-18 12:02:44 +08:00
"runtime/debug"
2024-01-22 18:05:51 +08:00
"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, ".")
by, _ := json.Marshal(v)
2024-01-23 00:12:08 +08:00
nowTime := time.Now().Local().Format("2006-01-02 15:04:05.000000")
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"
fd := FormatData{
Time: nowTime,
File: file + ":" + fmt.Sprintf("%d", line),
Func: funcName,
Gid: getGID(),
Content: string(by),
TraceId: traceId,
}
2024-04-18 12:02:44 +08:00
if event == "error" {
fd.Stack = string(debug.Stack())
}
2024-02-03 01:57:56 +08:00
fdb, _ := json.Marshal(fd)
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 {
Time string `json:"time,omitempty"`
File string `json:"file,omitempty"`
Func string `json:"func,omitempty"`
Gid string `json:"gid,omitempty"`
Content string `json:"content,omitempty"`
TraceId string `json:"traceId,omitempty"`
2024-04-18 12:02:44 +08:00
Stack string `json:"stack,omitempty"`
2024-02-03 01:57:56 +08:00
}