重构项目的实现,优化使用方法与使用逻辑
This commit is contained in:
@@ -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",
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user