feat: 为主程序添加日志文件输出和详细异常捕获机制
- 在 init() 函数中创建 logs 目录 - 配置日志输出到 logs/panic.log 文件 - 增强异常捕获逻辑,记录完整的堆栈信息和时间戳 - 优化 panic 恢复处理,提供更详细的错误追踪信息
This commit is contained in:
parent
db4d232464
commit
95333b37e6
27
main.go
27
main.go
@ -1,7 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"git.lxtend.com/qqbot/config"
|
||||
@ -12,11 +16,32 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 创建logs目录
|
||||
if err := os.MkdirAll("logs", 0755); err != nil {
|
||||
log.Printf("创建logs目录失败: %v", err)
|
||||
}
|
||||
|
||||
// 设置日志输出到文件
|
||||
logFile, err := os.OpenFile(filepath.Join("logs", "panic.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
log.Printf("打开日志文件失败: %v", err)
|
||||
return
|
||||
}
|
||||
log.SetOutput(logFile)
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 创建 WebSocket 客户端
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Print("Recovered in main:", err)
|
||||
// 获取详细的堆栈信息
|
||||
stack := debug.Stack()
|
||||
errMsg := fmt.Sprintf("[%s] Panic recovered:\nError: %v\nStack Trace:\n%s\n",
|
||||
time.Now().Format("2006-01-02 15:04:05"), err, stack)
|
||||
|
||||
// 写入日志文件
|
||||
log.Print(errMsg)
|
||||
}
|
||||
}()
|
||||
defer exec.DockerContainer.RemoveContainer()
|
||||
|
Loading…
x
Reference in New Issue
Block a user