From 0ab7960fcf84c38ea84708cfe5feb5729b11dae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E4=BA=AE?= Date: Sun, 3 Nov 2019 20:34:21 +0800 Subject: [PATCH] =?UTF-8?q?Add:=20=E8=87=AA=E5=AE=9A=E4=B9=89=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/util/error.go | 85 ++++++++++++++++++++++++++++++++++++++++ log/go-gin-api-error.log | 0 2 files changed, 85 insertions(+) create mode 100644 app/util/error.go create mode 100644 log/go-gin-api-error.log diff --git a/app/util/error.go b/app/util/error.go new file mode 100644 index 00000000..8b4295fb --- /dev/null +++ b/app/util/error.go @@ -0,0 +1,85 @@ +package util + +import ( + "fmt" + "go-gin-api/app/config" + "go-gin-api/app/route/middleware/exception" + "log" + "os" + "runtime/debug" + "strings" + "time" +) + +type errorString struct { + s string +} + +func (e *errorString) Error() string { + return e.s +} + +func ErrorNew (text string) error { + alarm("INFO", text) + return &errorString{text} +} + +// 发邮件 +func ErrorMail (text string) error { + alarm("MAIL",text) + return &errorString{text} +} + +// 发短信 +func ErrorSms (text string) error { + alarm("SMS", text) + return &errorString{text} +} + +// 发微信 +func ErrorWeChat (text string) error { + alarm("WX", text) + return &errorString{text} +} + +// 告警方法 +func alarm(level string, str string) { + if level == "MAIL" { + DebugStack := "" + for _, v := range strings.Split(string(debug.Stack()), "\n") { + DebugStack += v + "
" + } + + subject := fmt.Sprintf("【系统告警】%s 项目出错了!", config.AppName) + + body := strings.ReplaceAll(exception.MailTemplate, "{ErrorMsg}", fmt.Sprintf("%s", str)) + body = strings.ReplaceAll(body, "{RequestTime}", GetCurrentDate()) + body = strings.ReplaceAll(body, "{RequestURL}", "--") + body = strings.ReplaceAll(body, "{RequestUA}", "--") + body = strings.ReplaceAll(body, "{RequestIP}", "--") + body = strings.ReplaceAll(body, "{DebugStack}", DebugStack) + + // 执行发邮件 + _ = SendMail(config.ErrorNotifyUser, subject, body) + + } else if level == "SMS" { + // 执行发短信 + + } else if level == "WX" { + // 执行发微信 + + } else if level == "INFO" { + // 执行记日志 + + if f, err := os.OpenFile(config.AppErrorLogName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666); err != nil { + log.Println(err) + } else { + errorLogMap := make(map[string]interface{}) + errorLogMap["time"] = time.Now().Format("2006/01/02 - 15:04:05") + errorLogMap["info"] = str + + errorLogJson, _ := JsonEncode(errorLogMap) + _, _ = f.WriteString(errorLogJson + "\n") + } + } +} diff --git a/log/go-gin-api-error.log b/log/go-gin-api-error.log new file mode 100644 index 00000000..e69de29b