From 088d0f2708e87e6dc112c669f69ac28b04b2d49d Mon Sep 17 00:00:00 2001 From: iyear Date: Mon, 14 Jun 2021 13:07:08 +0800 Subject: [PATCH] change logger to zap --- bots/bots.go | 28 ++++++++++++-------------- bots/control.go | 45 ++++++++++++++++------------------------- bots/handle.go | 53 +++++++++++-------------------------------------- core/client.go | 2 +- go.mod | 2 +- main.go | 2 +- 6 files changed, 45 insertions(+), 87 deletions(-) diff --git a/bots/bots.go b/bots/bots.go index d9b9b39..0ae152c 100644 --- a/bots/bots.go +++ b/bots/bots.go @@ -5,9 +5,9 @@ import ( "fmt" "github.com/robfig/cron/v3" "github.com/spf13/viper" + "go.uber.org/zap" "golang.org/x/net/proxy" tb "gopkg.in/tucnak/telebot.v2" - "main/logger" "net/http" "strconv" "strings" @@ -38,12 +38,12 @@ var dbPath string func BotStart() { MakeHandle() TaskLaunch() - logger.Println("Bot Start") + fmt.Println("Bot Start") fmt.Println("------------") bot.Start() } func MakeHandle() { - logger.Println("Make Handle……") + fmt.Println("Make Handlers……") //所有用户 bot.Handle("/start", bStart) bot.Handle("/my", bMy) @@ -63,19 +63,19 @@ func TaskLaunch() { //log分为每天 //task.AddFunc(" 0 0 * * *", InitLogger) // */1 * * * * 1 */3 * * * - logger.Println("Cron Task Start……") + fmt.Println("Cron Task Start……") task.Start() } func init() { fmt.Println(logo) //read config - logger.Println("Read Config……") + fmt.Println("Read Config……") viper.SetConfigName("config") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { - logger.Println(err) + zap.S().Errorw("failed to read config","error",err) } host := viper.GetString("mysql.host") user := viper.GetString("mysql.user") @@ -86,17 +86,15 @@ func init() { //fmt.Println(path) db, err := sql.Open(dbDriverName, dbPath) if err != nil { - logger.Println(err) + zap.S().Errorw("failed to connect db","error",err,"path",dbPath) } - logger.Println("Connect MySQL Success!") + fmt.Println("Connect MySQL Success!") if ok, err := CreateTB(); !ok { - logger.Println(err) + zap.S().Errorw("failed to create table","error",err,"path",dbPath) } defer db.Close() BotToken = viper.GetString("bot_token") Socks5 = viper.GetString("socks5") - //set bot - logger.Println("Bot Settings……") Poller := &tb.LongPoller{Timeout: 15 * time.Second} spamProtected := tb.NewMiddlewarePoller(Poller, func(upd *tb.Update) bool { if upd.Message == nil { @@ -113,10 +111,10 @@ func init() { } //set socks5 if Socks5 != "" { - logger.Println("Proxy:" + Socks5) + fmt.Println("Proxy:" + Socks5) dialer, err := proxy.SOCKS5("tcp", Socks5, nil, proxy.Direct) if err != nil { - logger.Println(err) + zap.S().Errorw("failed to make dialer","error",err,"socks5",Socks5) } httpTransport := &http.Transport{} httpClient := &http.Client{Transport: httpTransport} @@ -126,7 +124,7 @@ func init() { //create bot bot, err = tb.NewBot(botsettings) if err != nil { - logger.Println(err) + zap.S().Errorw("failed to create bot","error",err) } - logger.Println("Bot: " + strconv.Itoa(bot.Me.ID) + " " + bot.Me.Username) + fmt.Println("Bot: " + strconv.Itoa(bot.Me.ID) + " " + bot.Me.Username) } diff --git a/bots/control.go b/bots/control.go index 726b02b..d1ca191 100644 --- a/bots/control.go +++ b/bots/control.go @@ -3,12 +3,12 @@ package bots import ( "errors" "fmt" + "github.com/iyear/E5SubBot/core" + "github.com/iyear/E5SubBot/util" "github.com/spf13/viper" "github.com/tidwall/gjson" + "go.uber.org/zap" tb "gopkg.in/tucnak/telebot.v2" - "main/core" - "main/logger" - "main/util" "strconv" "strings" "time" @@ -16,15 +16,12 @@ import ( var SignOk map[int64]int -//If Successfully return "",else return error information +// BindUser If Successfully return "",else return error information func BindUser(m *tb.Message, cid, cse string) error { - logger.Println("%d Begin Bind\n", m.Chat.ID) tmp := strings.Split(m.Text, " ") if len(tmp) != 2 { - logger.Println("%d Bind error:Wrong Bind Format\n", m.Chat.ID) - return errors.New("绑定格式错误") + return errors.New("wrong format") } - logger.Println("Alias: " + tmp[1]) Alias := tmp[1] client := core.NewClient(cid, cse) code := util.GetURLValue(tmp[0], "code") @@ -58,17 +55,16 @@ func BindUser(m *tb.Message, cid, cse string) error { if ok, err := core.AddData(u); !ok { return err } - logger.Println("%d Bind Successfully!\n", m.Chat.ID) return nil } -//get bind num +// GetBindNum get bind num func GetBindNum(TgId int64) int { data := core.QueryDataByTG(TgId) return len(data) } -//return true => exist +// MSAppIsExist return true => exist func MSAppIsExist(TgId int64, ClientId string) bool { data := core.QueryDataByTG(TgId) var res core.Client @@ -80,7 +76,6 @@ func MSAppIsExist(TgId int64, ClientId string) bool { return false } -//SignTask func SignTask() { var ( SignOk map[int64]int @@ -99,7 +94,7 @@ func SignTask() { pre := "您的账户: " + u.Alias + "\n在任务执行时出现了错误!\n错误:" chat, err := bot.ChatByID(strconv.FormatInt(u.TgId, 10)) if err != nil { - logger.Println(err) + zap.S().Errorw("wrong chat id","error",err,"tg_id",u.TgId) continue } //生成解绑按钮 @@ -112,8 +107,8 @@ func SignTask() { se := u.MsId + " ( @" + chat.Username + " )" client := core.NewClient(u.ClientId, u.ClientSecret) if err := client.GetOutlookMails(); err != nil { - logger.Println(u.MsId+" ", err) - bot.Send(chat, pre+gjson.Get(err.Error(), "error").String(), tmpBtn) + zap.S().Errorw("failed to get outlook mails","error",err,"ms_id",u.MsId) + bot.Send(chat, pre+err.Error(), tmpBtn) ErrorTimes[u.MsId]++ SignErr = append(SignErr, se) continue @@ -121,7 +116,7 @@ func SignTask() { u.Uptime = time.Now().Unix() u.RefreshToken = newRefreshToken if ok, err := core.UpdateData(u); !ok { - logger.Println(u.MsId+" ", err) + zap.S().Errorw("failed to update db data","error",err,"ms_id",u.MsId) bot.Send(chat, pre+err.Error(), tmpBtn) SignErr = append(SignErr, se) ErrorTimes[u.MsId]++ @@ -138,29 +133,23 @@ func SignTask() { for _, u := range data { chat, err := bot.ChatByID(strconv.FormatInt(u.TgId, 10)) if err != nil { - logger.Println("Send Result ERROR: ", err) + zap.S().Errorw("failed to get chat","error",err,"tg_id",u.TgId) continue } //错误上限账户清退 if ErrorTimes[u.MsId] == ErrMaxTimes { - logger.Println(u.MsId + " Error Limit") + zap.S().Errorw("binding max num limit","ms_id",u.MsId) if ok, err := core.DelData(u.MsId); !ok { - logger.Println(err) + zap.S().Errorw("failed to delete db data","error",err,"ms_id",u.MsId) } else { UnbindUser = append(UnbindUser, u.MsId+" ( @"+chat.Username+" )") - _, err = bot.Send(chat, "您的账户因达到错误上限而被自动解绑\n后会有期!\n\n别名: "+u.Alias+"\nclient_id: "+u.ClientId+"\nclient_secret: "+u.ClientSecret) - if err != nil { - logger.Println(err) - } + bot.Send(chat, "您的账户因达到错误上限而被自动解绑\n后会有期!\n\n别名: "+u.Alias+"\nclient_id: "+u.ClientId+"\nclient_secret: "+u.ClientSecret) } } if !isSend[u.TgId] { //静默发送,过多消息很烦 - _, err = bot.Send(chat, "任务反馈\n时间: "+time.Now().Format("2006-01-02 15:04:05")+"\n结果: "+strconv.Itoa(SignOk[u.TgId])+"/"+strconv.Itoa(GetBindNum(u.TgId)), &tb.SendOptions{DisableNotification: true}) - if err != nil { - logger.Println(err) - } + bot.Send(chat, "任务反馈\n时间: "+time.Now().Format("2006-01-02 15:04:05")+"\n结果: "+strconv.Itoa(SignOk[u.TgId])+"/"+strconv.Itoa(GetBindNum(u.TgId)), &tb.SendOptions{DisableNotification: true}) isSend[u.TgId] = true } } @@ -176,7 +165,7 @@ func SignTask() { for _, a := range admin { chat, err := bot.ChatByID(strconv.FormatInt(a, 10)) if err != nil { - logger.Println(err) + zap.S().Errorw("failed to get chat","error",err,"tg_id",a) continue } bot.Send(chat, "任务反馈(管理员)\n完成时间: "+time.Now().Format("2006-01-02 15:04:05")+"\n结果: "+strconv.Itoa(signOk)+"/"+strconv.Itoa(num)+"\n错误账户:\n"+ErrUserStr+"\n清退账户:\n"+UnbindUserStr) diff --git a/bots/handle.go b/bots/handle.go index 36ccd81..37af50a 100644 --- a/bots/handle.go +++ b/bots/handle.go @@ -3,12 +3,12 @@ package bots import ( "encoding/json" "github.com/fsnotify/fsnotify" + "github.com/iyear/E5SubBot/core" + "github.com/iyear/E5SubBot/util" "github.com/spf13/viper" + "go.uber.org/zap" tb "gopkg.in/tucnak/telebot.v2" "io/ioutil" - "main/core" - "main/logger" - "main/util" "os" "path/filepath" "strconv" @@ -82,7 +82,6 @@ func bStart(m *tb.Message) { } func bMy(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Manager Users") data := core.QueryDataByTG(m.Chat.ID) var inlineKeys [][]tb.InlineButton for _, u := range data { @@ -97,7 +96,6 @@ func bMy(m *tb.Message) { bot.Send(m.Chat, "选择一个账户查看具体信息\n\n绑定数: "+strconv.Itoa(GetBindNum(m.Chat.ID))+"/"+strconv.Itoa(BindMaxNum), &tb.ReplyMarkup{InlineKeyboard: inlineKeys}) } func bMyInlineBtn(c *tb.Callback) { - logger.Println(strconv.FormatInt(c.Message.Chat.ID, 10) + " Get User Info") r := core.QueryDataByMS(c.Data) u := r[0] bot.Send(c.Message.Chat, "信息\n别名:"+u.Alias+"\nMS_ID(MD5): "+u.MsId+"\nclient_id: "+u.ClientId+"\nclient_secret: "+u.ClientSecret+"\n最近更新时间: "+time.Unix(u.Uptime, 0).Format("2006-01-02 15:04:05")) @@ -105,33 +103,22 @@ func bMyInlineBtn(c *tb.Callback) { } func bBind1(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Bind") - logger.Println("ReApp: " + strconv.FormatInt(m.Chat.ID, 10)) bot.Send(m.Chat, "应用注册: [点击直达]("+core.GetMSRegisterAppUrl()+")", tb.ModeMarkdown) - _, err := bot.Send(m.Chat, "请回复client_id+空格+client_secret", &tb.ReplyMarkup{ForceReply: true}) - if err != nil { - logger.Println(err) - return - } + bot.Send(m.Chat, "请回复client_id+空格+client_secret", &tb.ReplyMarkup{ForceReply: true}) UserStatus[m.Chat.ID] = USBind1 UserCid[m.Chat.ID] = m.Text } func bBind2(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Bind2") - logger.Println("Auth: " + strconv.FormatInt(m.Chat.ID, 10)) tmp := strings.Split(m.Text, " ") if len(tmp) != 2 { - logger.Println("%d Bind error:Wrong Bind Format\n", m.Chat.ID) bot.Send(m.Chat, "错误的格式") return } - logger.Println("client_id: " + tmp[0] + " client_secret: " + tmp[1]) cid := tmp[0] cse := tmp[1] bot.Send(m.Chat, "授权账户: [点击直达]("+core.GetMSAuthUrl(cid)+")", tb.ModeMarkdown) _, err := bot.Send(m.Chat, "请回复http://localhost/…… + 空格 + 别名(用于管理)", &tb.ReplyMarkup{ForceReply: true}) if err != nil { - logger.Println(err) return } UserStatus[m.Chat.ID] = USBind2 @@ -140,7 +127,6 @@ func bBind2(m *tb.Message) { } func bUnBind(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Unbind") data := core.QueryDataByTG(m.Chat.ID) var inlineKeys [][]tb.InlineButton for _, u := range data { @@ -155,20 +141,17 @@ func bUnBind(m *tb.Message) { bot.Send(m.Chat, "选择一个账户将其解绑\n\n当前绑定数: "+strconv.Itoa(GetBindNum(m.Chat.ID))+"/"+strconv.Itoa(BindMaxNum), &tb.ReplyMarkup{InlineKeyboard: inlineKeys}) } func bUnBindInlineBtn(c *tb.Callback) { - logger.Println(strconv.FormatInt(c.Message.Chat.ID, 10) + " Unbind: " + c.Data) r := core.QueryDataByMS(c.Data) u := r[0] - if ok, _ := core.DelData(u.MsId); !ok { - logger.Println(u.MsId + " UnBind ERROR") + if ok, err := core.DelData(u.MsId); !ok { + zap.S().Errorw("failed to delete db data","error",err,"ms_id",u.MsId) bot.Send(c.Message.Chat, "解绑失败!") return } - logger.Println(u.MsId + " UnBind Success") bot.Send(c.Message.Chat, "解绑成功!") bot.Respond(c) } func bExport(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Export") type MsMiniData struct { Alias string ClientId string @@ -194,28 +177,22 @@ func bExport(m *tb.Message) { //MarshalIndent json美化,/t缩进 export, err := json.MarshalIndent(MsMini, "", "\t") if err != nil { - logger.Println(err) + zap.S().Errorw("failed to marshal json","error",err) bot.Send(m.Chat, "获取JSON失败~\n"+err.Error()) return } //fmt.Println(string(export)) fileName := "./" + strconv.FormatInt(m.Chat.ID, 10) + "_export_tmp.json" if err = ioutil.WriteFile(fileName, export, 0644); err != nil { - logger.Println(err) + zap.S().Errorw("failed to write file","error",err) bot.Send(m.Chat, "写入临时文件失败~\n"+err.Error()) return } exportFile := &tb.Document{File: tb.FromDisk(fileName), FileName: strconv.FormatInt(m.Chat.ID, 10) + ".json", MIME: "text/plain"} - _, err = bot.Send(m.Chat, exportFile) - if err != nil { - logger.Println(err) - return - } + bot.Send(m.Chat, exportFile) //不遗留本地文件 - if exportFile.InCloud() == true && os.Remove(fileName) == nil { - logger.Println(fileName + " Has Removed") - } else { - logger.Println(fileName + " Removed ERROR") + if exportFile.InCloud() != true || os.Remove(fileName) != nil { + zap.S().Errorw("failed to export files") } } func bHelp(m *tb.Message) { @@ -258,7 +235,6 @@ func bOnText(m *tb.Message) { } } func bTask(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start SignTask") for _, a := range admin { if a == m.Chat.ID { SignTask() @@ -268,7 +244,6 @@ func bTask(m *tb.Message) { bot.Send(m.Chat, "您没有权限执行此操作~") } func bLog(m *tb.Message) { - logger.Println(strconv.FormatInt(m.Chat.ID, 10) + " Start Get Logs") flag := 0 for _, a := range admin { if a == m.Chat.ID { @@ -290,13 +265,9 @@ func bLog(m *tb.Message) { bot.Handle(&inlineBtn, bLogsInlineBtn) inlineKeys = append(inlineKeys, []tb.InlineButton{inlineBtn}) } - _, err := bot.Send(m.Chat, "选择一个日志", &tb.ReplyMarkup{InlineKeyboard: inlineKeys}) - if err != nil { - logger.Println(err) - } + bot.Send(m.Chat, "选择一个日志", &tb.ReplyMarkup{InlineKeyboard: inlineKeys}) } func bLogsInlineBtn(c *tb.Callback) { - logger.Println(strconv.FormatInt(c.Message.Chat.ID, 10) + " Get Logs: " + c.Data) //fmt.Println(c.Data) //logger.Println(bLogBasePath + c.Data + ".log") logfile := &tb.Document{File: tb.FromDisk(bLogBasePath + c.Data), FileName: c.Data, MIME: "text/plain"} diff --git a/core/client.go b/core/client.go index a8b2df2..ea55f53 100644 --- a/core/client.go +++ b/core/client.go @@ -156,5 +156,5 @@ func (c *Client) GetOutlookMails() error { if gjson.Get(string(content), "@odata\\.context").String() != "" { return nil } - return errors.New(string(content)) + return errors.New(gjson.Get(string(content), "error").String()) } diff --git a/go.mod b/go.mod index 3e87cd1..75ac59c 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module main +module github.com/iyear/E5SubBot go 1.13 diff --git a/main.go b/main.go index 82e01da..43a131a 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,6 @@ package main -import "main/bots" +import "github.com/iyear/E5SubBot/bots" func main() { bots.BotStart()