From 2db2f413a1b9618758a8029e493191ad0dfbc25a Mon Sep 17 00:00:00 2001 From: ShenQiLun <97694732@qq.com> Date: Fri, 26 Jun 2026 16:28:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=97=A5=E5=BF=97=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E5=90=8C=E6=97=B6=E8=BE=93=E5=87=BA=E5=88=B0GUI=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E5=92=8Clog/=E6=97=A5=E6=9C=9F.log=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/server/gui_windows.go | 43 +++++++++++++++++++++++++++++++++++++++ cmd/server/main.go | 7 ++++--- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/cmd/server/gui_windows.go b/cmd/server/gui_windows.go index 4332a72..ba651c1 100644 --- a/cmd/server/gui_windows.go +++ b/cmd/server/gui_windows.go @@ -4,11 +4,13 @@ package main import ( "fmt" + "io" "log" "os" "runtime" "sync" "syscall" + "time" "unsafe" ) @@ -139,6 +141,47 @@ func (w *guiLogWriter) Write(p []byte) (n int, err error) { return len(p), nil } +// logFileWriter 实现 io.Writer,将日志写入 log/日期.log 文件 +type logFileWriter struct { + mu sync.Mutex + curDate string + curFile *os.File +} + +func (w *logFileWriter) Write(p []byte) (n int, err error) { + w.mu.Lock() + defer w.mu.Unlock() + + date := time.Now().Format("2006-01-02") + if date != w.curDate || w.curFile == nil { + if w.curFile != nil { + w.curFile.Close() + w.curFile = nil + } + if err := os.MkdirAll("./log", 0755); err != nil { + return 0, err + } + filename := fmt.Sprintf("./log/%s.log", date) + f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return 0, err + } + w.curDate = date + w.curFile = f + } + + return w.curFile.Write(p) +} + +// initFileLog 初始化文件日志,返回 io.Writer +func initFileLog() io.Writer { + w := &logFileWriter{} + // 写入一条启动标记 + now := time.Now().Format("2006-01-02 15:04:05") + w.Write([]byte(fmt.Sprintf("====== %s 日志文件初始化完成 ======\n", now))) + return w +} + func appendText(text string) { if hWndEdit == 0 { return diff --git a/cmd/server/main.go b/cmd/server/main.go index bf488ee..b81208b 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -3,6 +3,7 @@ package main import ( "encoding/json" "fmt" + "io" "log" "net/http" @@ -14,8 +15,8 @@ import ( ) func main() { - // 日志输出到GUI窗口 - log.SetOutput(&guiLogWriter{}) + // 日志同时输出到GUI窗口和本地文件 + log.SetOutput(io.MultiWriter(&guiLogWriter{}, initFileLog())) log.Printf("孔网商品定价 %s 启动中...", version) @@ -29,7 +30,7 @@ func main() { global := config.GetGlobal() marshal, _ := json.Marshal(global) - fmt.Println("config:", string(marshal)) + log.Printf("config: %s", string(marshal)) // 初始化数据库 if err := database.InitDB("./data/goods_pricing.db"); err != nil {