chore(init): 初始化解忧商行项目并完成 Phase 0 基座
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
func New(cfg config.LogConfig) (*zap.Logger, error) {
|
||||
location, err := time.LoadLocation("Asia/Shanghai")
|
||||
if err != nil {
|
||||
location = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
}
|
||||
|
||||
level := zap.NewAtomicLevelAt(parseLevel(cfg.Level))
|
||||
cores := make([]zapcore.Core, 0, 2)
|
||||
if cfg.EnableConsole {
|
||||
cores = append(cores, zapcore.NewCore(
|
||||
newTextEncoder(location),
|
||||
zapcore.Lock(os.Stdout),
|
||||
level,
|
||||
))
|
||||
}
|
||||
if cfg.EnableFile {
|
||||
writer := newDailyWriter(cfg.Dir, "app", location, cfg.RetainDays)
|
||||
if err := writer.Open(); err != nil {
|
||||
return nil, fmt.Errorf("初始化日志文件失败: %w", err)
|
||||
}
|
||||
cores = append(cores, zapcore.NewCore(
|
||||
newTextEncoder(location),
|
||||
writer,
|
||||
level,
|
||||
))
|
||||
}
|
||||
if len(cores) == 0 {
|
||||
cores = append(cores, zapcore.NewCore(
|
||||
newTextEncoder(location),
|
||||
zapcore.Lock(os.Stdout),
|
||||
level,
|
||||
))
|
||||
}
|
||||
|
||||
logger := zap.New(
|
||||
zapcore.NewTee(cores...),
|
||||
zap.AddCaller(),
|
||||
zap.AddStacktrace(zapcore.PanicLevel),
|
||||
zap.ErrorOutput(zapcore.Lock(os.Stderr)),
|
||||
)
|
||||
zap.ReplaceGlobals(logger)
|
||||
return logger, nil
|
||||
}
|
||||
|
||||
func parseLevel(value string) zapcore.Level {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "debug":
|
||||
return zapcore.DebugLevel
|
||||
case "warn", "warning":
|
||||
return zapcore.WarnLevel
|
||||
case "error":
|
||||
return zapcore.ErrorLevel
|
||||
default:
|
||||
return zapcore.InfoLevel
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user