Files
learn-golang/Web开发/05go-zap-demo/03zap_custom.go
liumangmang b010f82221 feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能
- 集成Gin、GORM、Viper、Zap等框架
- 添加密码加密、数据库操作、中间件等完整功能
- 配置多环境支持、日志轮转、CORS处理
- 创建完整的项目结构和配置文件体系
2025-12-30 18:00:42 +08:00

52 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func main() {
// 1. 自定义配置
config := zap.Config{
Level: zap.NewAtomicLevelAt(zap.InfoLevel), // 日志级别
Development: false, // 生产模式
Encoding: "json", // 输出格式json/console
OutputPaths: []string{"stdout", "app.log"}, // 输出到控制台和文件
ErrorOutputPaths: []string{"stderr"},
EncoderConfig: zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写级别名
EncodeTime: zapcore.ISO8601TimeEncoder, // ISO8601 时间格式
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder, // 短路径
},
}
// 2. 创建 Logger
logger, _ := config.Build()
defer logger.Sync()
// 3. 使用 Logger
logger.Info("Custom logger initialized",
zap.String("env", "production"),
zap.Int("workers", 10),
)
logger.Warn("Low disk space",
zap.Int64("available_mb", 500),
zap.Int64("threshold_mb", 1000),
)
logger.Error("Database connection failed",
zap.String("host", "localhost"),
zap.Int("port", 3306),
zap.Error(nil),
)
}