重构项目的实现,优化使用方法与使用逻辑

This commit is contained in:
2026-06-25 00:03:59 +08:00
parent a6e8101e09
commit 6072ec57e8
49 changed files with 1663 additions and 12534 deletions

View File

@@ -1,3 +1,6 @@
//go:build example
// +build example
package main
import (
@@ -8,57 +11,24 @@ import (
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config/example.json")
if err != nil {
log.Fatal("Failed to load config:", err)
log.Fatal(err)
}
// 方式1使用工厂创建日志记录器推荐方式
fac := factory.NewFactory(cfg)
logger, err := fac.GetLogger()
app := factory.New(cfg)
logInst, err := app.Logger()
if err != nil {
log.Fatal("Failed to create logger:", err)
log.Fatal(err)
}
defer logInst.Close()
// 如果使用异步模式程序退出前需要关闭logger
defer logger.Close()
// 方式2直接使用工厂的日志方法黑盒模式更简单
// fac.LogInfo("Application started")
// fac.LogError("An error occurred")
// 示例1基本日志记录
logger.Info("Application started")
logger.Debug("Debug message: %s", "This is a debug message")
logger.Warn("Warning message: %s", "This is a warning")
logger.Error("Error message: %s", "This is an error")
// 示例2带字段的日志记录
logger.Infof(map[string]interface{}{
logInst.Info("Application started", nil)
logInst.Info("User logged in", map[string]any{
"user_id": 123,
"action": "login",
"ip": "192.168.1.1",
}, "User logged in successfully")
logger.Errorf(map[string]interface{}{
"error_code": 1001,
"module": "database",
}, "Failed to connect to database: %v", "connection timeout")
// 示例3不同级别的日志
logger.Debug("This is a debug log")
logger.Info("This is an info log")
logger.Warn("This is a warn log")
logger.Error("This is an error log")
// 示例4异步模式使用
// 如果配置中设置了 "async": true日志会异步写入
// 程序退出前需要调用 Close() 确保所有日志写入完成
// logger.Close()
// 注意Fatal和Panic会终止程序示例中不执行
// logger.Fatal("This would exit the program")
// logger.Panic("This would panic")
})
logInst.Error("Failed to connect to database", map[string]any{
"error": "connection timeout",
})
}