Files
learn-golang/go-mini-logger/main.go
2025-12-26 17:56:02 +08:00

36 lines
1.1 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.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("=== 1. 控制台日志 ===")
consoleLogger := NewLogger()
consoleLogger.Info("程序启动PID: %d", os.Getpid())
consoleLogger.Warn("磁盘使用率超过 80%")
consoleLogger.Error("数据库连接失败: timeout")
fmt.Println("\n=== 2. 设置最低级别为 WARN ===")
consoleLogger.SetMinLevel(LevelWarn)
consoleLogger.Info("这条不会显示") // 被过滤
consoleLogger.Warn("这条会显示") // 显示
consoleLogger.Error("错误也会显示") // 显示
fmt.Println("\n=== 3. 文件日志(写入 app.log===")
fileLogger, err := NewFileLogger("app.log")
if err != nil {
consoleLogger.Error("无法创建文件日志: %v", err)
return
}
fileLogger.Info("应用开始处理请求")
fileLogger.Warn("用户 %s 尝试越权操作", "liumangmang")
fileLogger.Error("写入数据库时发生唯一键冲突")
fmt.Println("日志已写入 app.log请查看内容")
os.ReadFile("app.log") // 不打印,仅确保写入
fmt.Println("✅ 查看 app.log 可验证文件日志内容")
}