1 Star 0 Fork 0

igo/pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
caller.go 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
layte.xiao 提交于 2025-05-29 23:13 +08:00 . 优化日志
package xlog
import (
"fmt"
"log/slog"
"path/filepath"
"runtime"
"slices"
)
func caller(skip int) *slog.Source {
var pc uintptr
var pcs [1]uintptr
runtime.Callers(3+skip, pcs[:])
pc = pcs[0]
fs := runtime.CallersFrames([]uintptr{pc})
f, _ := fs.Next()
return &slog.Source{
Function: f.Function,
File: filepath.Base(f.File) + ":" + fmt.Sprintf("%d", f.Line),
}
}
func addCaller(skip int, attrs ...slog.Attr) []slog.Attr {
if slices.ContainsFunc(attrs, func(item slog.Attr) bool {
return item.Key == "caller"
}) {
return attrs
}
source := caller(2)
attrs = append(attrs, slog.String("caller", source.File))
return attrs
}
func sortAttrs(attrs []slog.Attr) []slog.Attr {
listMap := make(map[string]slog.Attr)
for _, v := range attrs {
listMap[v.Key] = v
}
listMap["caller"] = slog.Any("caller", caller(2))
field := []string{"time", "level", "caller", "msg"}
list := make([]slog.Attr, len(field))
for idx, v := range field {
list[idx] = listMap[v]
}
for _, v := range attrs {
if slices.Contains([]string{"time", "level", "caller", "msg"}, v.Key) {
continue
}
list = append(list, v)
}
return list
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/igolang/pkg.git
git@gitee.com:igolang/pkg.git
igolang
pkg
pkg
v1.29.8

搜索帮助