pkg/logger/logger.go

37 lines
709 B
Go

// Package logger provider std slog logger
package logger
import (
"log/slog"
"os"
"path/filepath"
"strconv"
)
// Init 初始化 slog
func Init() {
textHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
ReplaceAttr: ReplaceSourceAttr,
})
logger := slog.New(textHandler)
slog.SetDefault(logger)
}
// ReplaceSourceAttr source 格式化为 dir/file:line 格式
func ReplaceSourceAttr(groups []string, a slog.Attr) slog.Attr {
if a.Key != slog.SourceKey {
return a
}
src, ok := a.Value.Any().(*slog.Source)
if !ok {
return a
}
a.Value = slog.StringValue(filepath.Base(src.File) + ":" + strconv.Itoa(src.Line))
return a
}