topfans/backend/pkg/logger/logger_test.go
2026-04-07 22:29:48 +08:00

66 lines
1.5 KiB
Go

package logger
import (
"os"
"testing"
"go.uber.org/zap"
)
// TestLoggerInit 测试logger初始化
func TestLoggerInit(t *testing.T) {
// 测试开发环境
err := Init(Config{
ServiceName: "test-service",
Environment: "development",
LogLevel: "debug",
})
if err != nil {
t.Fatalf("Failed to initialize logger: %v", err)
}
defer Sync()
// 测试各种日志级别
Sugar.Debug("This is a debug message")
Sugar.Info("This is an info message")
Sugar.Warn("This is a warn message")
Sugar.Error("This is an error message")
// 测试结构化日志
Logger.Info("User registered",
zap.String("mobile", "13800138000"),
zap.Int64("user_id", 123),
zap.Int64("star_id", 456),
)
// 测试带格式的日志
Sugar.Infof("Processing request: mobile=%s, user_id=%d", "13800138000", 123)
}
// TestLoggerProduction 测试生产环境配置
func TestLoggerProduction(t *testing.T) {
// 临时创建测试日志目录
testLogPath := "test-logs"
defer os.RemoveAll(testLogPath)
err := Init(Config{
ServiceName: "test-service",
Environment: "production",
LogLevel: "info",
LogPath: testLogPath,
})
if err != nil {
t.Fatalf("Failed to initialize logger: %v", err)
}
defer Sync()
// 测试日志输出
Sugar.Info("Production log test")
Sugar.Error("Production error log test")
// 验证日志文件是否创建
if _, err := os.Stat(testLogPath + "/test-service.log"); os.IsNotExist(err) {
t.Log("Warning: Log file not created (this is OK if only stdout is used)")
}
}