feat: 新增日志、配置文件和环境变量

This commit is contained in:
2026-03-02 02:01:08 +08:00
commit 607ff9a055
10 changed files with 1085 additions and 0 deletions

92
logger/encoder.go Normal file
View File

@@ -0,0 +1,92 @@
package logger
import (
"go.uber.org/zap/zapcore"
)
// EncoderType represents the log encoder type
type EncoderType string
const (
// JSONEncoder encodes logs as JSON
JSONEncoder EncoderType = "json"
// ConsoleEncoder encodes logs as human-readable text
ConsoleEncoder EncoderType = "console"
)
// NewEncoderConfig returns a default encoder config
func NewEncoderConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
FunctionKey: zapcore.OmitKey,
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
}
// newConsoleEncoderConfig returns a colored encoder config for console output
func newConsoleEncoderConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
FunctionKey: zapcore.OmitKey,
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: CustomLevelEncoder, // 自定义带颜色的级别编码
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
}
// NewJSONEncoder creates a new JSON encoder
func NewJSONEncoder() zapcore.Encoder {
return zapcore.NewJSONEncoder(NewEncoderConfig())
}
// NewConsoleEncoder creates a new console encoder with colors
func NewConsoleEncoder() zapcore.Encoder {
return zapcore.NewConsoleEncoder(newConsoleEncoderConfig())
}
// NewEncoder creates an encoder based on the given type
// Defaults to console encoder if type is invalid
func NewEncoder(encoderType EncoderType) zapcore.Encoder {
switch encoderType {
case JSONEncoder:
return NewJSONEncoder()
case ConsoleEncoder:
return NewConsoleEncoder()
default:
return NewConsoleEncoder()
}
}
// CustomLevelEncoder creates a custom level encoder with colors and styles
func CustomLevelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
switch l {
case zapcore.DebugLevel:
enc.AppendString("\x1b[37m" + l.CapitalString() + "\x1b[0m") // 白色
case zapcore.InfoLevel:
enc.AppendString("\x1b[32m" + l.CapitalString() + "\x1b[0m") // 绿色
case zapcore.WarnLevel:
enc.AppendString("\x1b[33m" + l.CapitalString() + "\x1b[0m") // 黄色
case zapcore.ErrorLevel:
enc.AppendString("\x1b[31m" + l.CapitalString() + "\x1b[0m") // 红色
case zapcore.FatalLevel:
enc.AppendString("\x1b[35m" + l.CapitalString() + "\x1b[0m") // 紫色
default:
enc.AppendString(l.CapitalString())
}
}