Files
go-common/examples/logger_example.go
2025-11-30 13:43:43 +08:00

53 lines
1.3 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 (
"log"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/factory"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config/example.json")
if err != nil {
log.Fatal("Failed to load config:", err)
}
// 使用工厂创建日志记录器(推荐方式)
fac := factory.NewFactory(cfg)
logger, err := fac.GetLogger()
if err != nil {
log.Fatal("Failed to create logger:", err)
}
// 示例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{}{
"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")
// 注意Fatal和Panic会终止程序示例中不执行
// logger.Fatal("This would exit the program")
// logger.Panic("This would panic")
}