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

89 lines
2.2 KiB
Go
Raw 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.

// +build ignore
// 这是一个独立的测试程序,用于测试日志输出
package main
import (
"fmt"
"os"
"time"
"github.com/topfans/backend/pkg/logger"
"go.uber.org/zap"
)
func main() {
fmt.Println("=== 测试Logger初始化 ===")
// 测试开发环境
fmt.Println("\n1. 测试开发环境(彩色控制台输出):")
err := logger.Init(logger.Config{
ServiceName: "user-service",
Environment: "development",
LogLevel: "debug",
})
if err != nil {
panic(fmt.Sprintf("Failed to initialize logger: %v", err))
}
defer logger.Sync()
// 测试各种日志级别
logger.Sugar.Debug("This is a debug message")
logger.Sugar.Info("This is an info message")
logger.Sugar.Warn("This is a warn message")
logger.Sugar.Error("This is an error message")
// 测试结构化日志
logger.Logger.Info("User registered",
zap.String("mobile", "13800138000"),
zap.Int64("user_id", 123),
zap.Int64("star_id", 456),
)
// 测试带格式的日志
logger.Sugar.Infof("Processing request: mobile=%s, user_id=%d", "13800138000", 123)
// 测试错误日志
logger.Logger.Error("Failed to create user",
zap.String("mobile", "13800138000"),
zap.Error(fmt.Errorf("user already exists")),
)
fmt.Println("\n2. 测试生产环境JSON格式 + 文件输出):")
// 重新初始化生产环境配置
logger.Sync() // 先关闭之前的logger
testLogPath := "test-logs"
err = logger.Init(logger.Config{
ServiceName: "user-service",
Environment: "production",
LogLevel: "info",
LogPath: testLogPath,
})
if err != nil {
panic(fmt.Sprintf("Failed to initialize logger: %v", err))
}
defer logger.Sync()
defer os.RemoveAll(testLogPath) // 清理测试日志文件
logger.Logger.Info("User login successful",
zap.Int64("user_id", 123),
zap.Int64("star_id", 456),
zap.String("mobile", "13800138000"),
)
logger.Logger.Error("Database connection failed",
zap.String("error", "connection timeout"),
zap.String("host", "localhost"),
zap.Int("port", 5432),
)
// 等待一下,确保日志写入
time.Sleep(100 * time.Millisecond)
fmt.Println("\n✅ 日志测试完成!")
fmt.Printf("📁 生产环境日志文件位置: %s/user-service.log\n", testLogPath)
}