From 23d952ee658f711ba201a161aadaa9e20cfff493 Mon Sep 17 00:00:00 2001 From: toeasy Date: Mon, 17 Apr 2023 21:17:11 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=BC=95=E5=85=A5=E6=97=A5=E5=BF=97logrus?= =?UTF-8?q?=EF=BC=8C=E5=B9=B6=E5=BC=80=E5=90=AF=E4=BA=86larksuite=E7=9A=84?= =?UTF-8?q?debug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- code/go.mod | 1 + code/go.sum | 3 + code/handlers/card_clear_action.go | 8 +- code/handlers/card_common_action.go | 2 + code/handlers/card_pic_action.go | 10 ++- code/handlers/event_common_action.go | 1 + code/handlers/event_pic_action.go | 3 +- code/handlers/handler.go | 5 +- code/handlers/init.go | 5 +- code/handlers/msg.go | 8 +- code/initialization/gin.go | 3 +- code/initialization/lark_client.go | 6 +- code/logger/logger.go | 115 +++++++++++++++++++++++++++ code/main.go | 8 +- code/services/openai/common.go | 9 ++- code/services/openai/gpt3.go | 4 + 16 files changed, 170 insertions(+), 21 deletions(-) create mode 100644 code/logger/logger.go diff --git a/code/go.mod b/code/go.mod index 0ddc315d..8eae9efe 100644 --- a/code/go.mod +++ b/code/go.mod @@ -12,6 +12,7 @@ require ( github.com/pandodao/tokenizer-go v0.2.0 github.com/patrickmn/go-cache v2.1.0+incompatible github.com/pion/opus v0.0.0-20230123082803-1052c3e89e58 + github.com/sirupsen/logrus v1.9.0 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.14.0 gopkg.in/yaml.v2 v2.4.0 diff --git a/code/go.sum b/code/go.sum index 7f870c9b..301f587d 100644 --- a/code/go.sum +++ b/code/go.sum @@ -217,6 +217,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= @@ -396,6 +398,7 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/code/handlers/card_clear_action.go b/code/handlers/card_clear_action.go index 51bd582b..c1c1ab26 100644 --- a/code/handlers/card_clear_action.go +++ b/code/handlers/card_clear_action.go @@ -2,10 +2,9 @@ package handlers import ( "context" - - "start-feishubot/services" - larkcard "github.com/larksuite/oapi-sdk-go/v3/card" + "start-feishubot/logger" + "start-feishubot/services" ) func NewClearCardHandler(cardMsg CardMsg, m MessageHandler) CardHandlerFunc { @@ -23,6 +22,7 @@ func NewClearCardHandler(cardMsg CardMsg, m MessageHandler) CardHandlerFunc { func CommonProcessClearCache(cardMsg CardMsg, session services.SessionServiceCacheInterface) ( interface{}, error, bool) { + logger.Debugf("card msg value %v", cardMsg.Value) if cardMsg.Value == "1" { session.Clear(cardMsg.SessionId) newCard, _ := newSendCard( @@ -30,7 +30,7 @@ func CommonProcessClearCache(cardMsg CardMsg, session services.SessionServiceCac withMainMd("已删除此话题的上下文信息"), withNote("我们可以开始一个全新的话题,继续找我聊天吧"), ) - //fmt.Printf("session: %v", newCard) + logger.Debugf("session %v", newCard) return newCard, nil, true } if cardMsg.Value == "0" { diff --git a/code/handlers/card_common_action.go b/code/handlers/card_common_action.go index 7d89eefd..29ef6a8e 100644 --- a/code/handlers/card_common_action.go +++ b/code/handlers/card_common_action.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "start-feishubot/logger" larkcard "github.com/larksuite/oapi-sdk-go/v3/card" ) @@ -34,6 +35,7 @@ func NewCardHandler(m MessageHandler) CardHandlerFunc { return nil, err } //pp.Println(cardMsg) + logger.Debug("cardMsg ", cardMsg) for _, handler := range handlers { h := handler(cardMsg, m) i, err := h(ctx, cardAction) diff --git a/code/handlers/card_pic_action.go b/code/handlers/card_pic_action.go index 9e4a33b9..2c2d1902 100644 --- a/code/handlers/card_pic_action.go +++ b/code/handlers/card_pic_action.go @@ -2,6 +2,9 @@ package handlers import ( "context" + "fmt" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" + "start-feishubot/logger" "start-feishubot/services" @@ -47,7 +50,7 @@ func CommonProcessPicResolution(msg CardMsg, cardAction *larkcard.CardAction, cache services.SessionServiceCacheInterface) { option := cardAction.Action.Option - //fmt.Println(larkcore.Prettify(msg)) + fmt.Println(larkcore.Prettify(msg)) cache.SetPicResolution(msg.SessionId, services.Resolution(option)) //send text replyMsg(context.Background(), "已更新图片分辨率为"+option, @@ -56,8 +59,9 @@ func CommonProcessPicResolution(msg CardMsg, func (m MessageHandler) CommonProcessPicMore(msg CardMsg) { resolution := m.sessionCache.GetPicResolution(msg.SessionId) - //fmt.Println("resolution: ", resolution) - //fmt.Println("msg: ", msg) + + logger.Debugf("resolution: %v", resolution) + logger.Debug("msg: %v", msg) question := msg.Value.(string) bs64, _ := m.gpt.GenerateOneImage(question, resolution) replayImageCardByBase64(context.Background(), bs64, &msg.MsgId, diff --git a/code/handlers/event_common_action.go b/code/handlers/event_common_action.go index 4f79e163..d6827b52 100644 --- a/code/handlers/event_common_action.go +++ b/code/handlers/event_common_action.go @@ -69,6 +69,7 @@ func (*EmptyAction) Execute(a *ActionInfo) bool { sendMsg(*a.ctx, "🤖️:你想知道什么呢~", a.info.chatId) fmt.Println("msgId", *a.info.msgId, "message.text is empty") + return false } return true diff --git a/code/handlers/event_pic_action.go b/code/handlers/event_pic_action.go index 0fb69395..c3dedfdd 100644 --- a/code/handlers/event_pic_action.go +++ b/code/handlers/event_pic_action.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "start-feishubot/logger" "start-feishubot/initialization" "start-feishubot/services" @@ -36,7 +37,7 @@ func (*PicAction) Execute(a *ActionInfo) bool { mode := a.handler.sessionCache.GetMode(*a.info.sessionId) //fmt.Println("mode: ", mode) - + logger.Debug("MODE:", mode) // 收到一张图片,且不在图片创作模式下, 提醒是否切换到图片创作模式 if a.info.msgType == "image" && mode != services.ModePicCreate { sendPicModeCheckCard(*a.ctx, a.info.sessionId, a.info.msgId) diff --git a/code/handlers/handler.go b/code/handlers/handler.go index c3286f26..cfdc8070 100644 --- a/code/handlers/handler.go +++ b/code/handlers/handler.go @@ -3,6 +3,8 @@ package handlers import ( "context" "fmt" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" + "start-feishubot/logger" "strings" "start-feishubot/initialization" @@ -49,11 +51,12 @@ func judgeMsgType(event *larkim.P2MessageReceiveV1) (string, error) { func (m MessageHandler) msgReceivedHandler(ctx context.Context, event *larkim.P2MessageReceiveV1) error { handlerType := judgeChatType(event) + logger.Debug("handlerType", handlerType) if handlerType == "otherChat" { fmt.Println("unknown chat type") return nil } - //fmt.Println(larkcore.Prettify(event.Event.Message)) + logger.Debug("收到消息:", larkcore.Prettify(event.Event.Message)) msgType, err := judgeMsgType(event) if err != nil { diff --git a/code/handlers/init.go b/code/handlers/init.go index 5589359c..25ab953a 100644 --- a/code/handlers/init.go +++ b/code/handlers/init.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "start-feishubot/logger" "start-feishubot/initialization" "start-feishubot/services/openai" @@ -34,8 +35,10 @@ func Handler(ctx context.Context, event *larkim.P2MessageReceiveV1) error { } func ReadHandler(ctx context.Context, event *larkim.P2MessageReadV1) error { - _ = event.Event.Reader.ReaderId.OpenId + readerId := event.Event.Reader.ReaderId.OpenId //fmt.Printf("msg is read by : %v \n", *readerId) + logger.Debugf("msg is read by : %v \n", *readerId) + return nil } diff --git a/code/handlers/msg.go b/code/handlers/msg.go index 18ab272e..21610530 100644 --- a/code/handlers/msg.go +++ b/code/handlers/msg.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "errors" "fmt" + "start-feishubot/logger" "start-feishubot/initialization" "start-feishubot/services" @@ -70,7 +71,7 @@ func replyCard(ctx context.Context, // 服务端错误处理 if !resp.Success() { - fmt.Println(resp.Code, resp.Msg, resp.RequestId()) + logger.Errorf("服务端错误 resp code[%v], msg [%v] requestId [%v] ", resp.Code, resp.Msg, resp.RequestId()) return errors.New(resp.Msg) } return nil @@ -758,7 +759,10 @@ func SendRoleTagsCard(ctx context.Context, withHeader("🛖 请选择角色类别", larkcard.TemplateIndigo), withRoleTagsBtn(sessionId, roleTags...), withNote("提醒:选择角色所属分类,以便我们为您推荐更多相关角色。")) - replyCard(ctx, msgId, newCard) + err := replyCard(ctx, msgId, newCard) + if err != nil { + logger.Errorf("选择角色出错 %v", err) + } } func SendRoleListCard(ctx context.Context, diff --git a/code/initialization/gin.go b/code/initialization/gin.go index cdc93234..59e19749 100644 --- a/code/initialization/gin.go +++ b/code/initialization/gin.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "net/http" + //"start-feishubot/logger" "time" "github.com/gin-gonic/gin" @@ -35,7 +36,7 @@ func loadCertificate(config Config) (cert tls.Certificate, err error) { } func startHTTPServer(config Config, r *gin.Engine) (err error) { - log.Printf("http server started: http://localhost:%d/webhook/event\n", config.HttpPort) + log.Printf("http server started: http://localhost:%d/webhook/event\n\n", config.HttpPort) err = r.Run(fmt.Sprintf(":%d", config.HttpPort)) if err != nil { return fmt.Errorf("failed to start http server: %v", err) diff --git a/code/initialization/lark_client.go b/code/initialization/lark_client.go index 27ad97d5..5a0b27b1 100644 --- a/code/initialization/lark_client.go +++ b/code/initialization/lark_client.go @@ -2,12 +2,16 @@ package initialization import ( lark "github.com/larksuite/oapi-sdk-go/v3" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" ) var larkClient *lark.Client func LoadLarkClient(config Config) { - larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret) + + option := lark.WithLogLevel(larkcore.LogLevelDebug) + larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret, option) + } func GetLarkClient() *lark.Client { diff --git a/code/logger/logger.go b/code/logger/logger.go new file mode 100644 index 00000000..d42d7117 --- /dev/null +++ b/code/logger/logger.go @@ -0,0 +1,115 @@ +package logger + +import ( + "bytes" + "github.com/gin-gonic/gin" + "github.com/sirupsen/logrus" + "strings" +) + +var logger = logrus.New() + +func init() { + + logger.SetFormatter(&formatter{}) + + logger.SetReportCaller(true) + + gin.DefaultWriter = logger.Out + + logger.Level = logrus.DebugLevel + +} + +type Fields logrus.Fields + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + if logger.Level >= logrus.DebugLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Debugf(format, args...) + } +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + if logger.Level >= logrus.WarnLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Warnf(format, args...) + } +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + if logger.Level >= logrus.ErrorLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Errorf(format, args...) + } +} + +// Fatalf logs a message at level Fatal on the standard logger. +func Fatalf(format string, args ...interface{}) { + if logger.Level >= logrus.FatalLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Fatalf(format, args...) + } +} + +func Debug(format string, args ...interface{}) { + if logger.Level >= logrus.DebugLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Debug(format, args) + } +} + +// Info logs a message at level Info on the standard logger. +func Info(format string, args ...interface{}) { + if logger.Level >= logrus.InfoLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Info(format, args) + } +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(format string, args ...interface{}) { + if logger.Level >= logrus.WarnLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Warn(format, args) + } +} + +// Error logs a message at level Error on the standard logger. +func Error(format string, args ...interface{}) { + if logger.Level >= logrus.ErrorLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Error(format, args) + } +} + +// Fatal logs a message at level Fatal on the standard logger. +func Fatal(format string, args ...interface{}) { + if logger.Level >= logrus.FatalLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Fatal(format, args) + } +} + +// Formatter implements logrus.Formatter interface. +type formatter struct { + prefix string +} + +// Format building log message. +func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) { + var sb bytes.Buffer + + sb.WriteString("[" + strings.ToUpper(entry.Level.String()) + "]") + sb.WriteString(entry.Time.Format("2006-01-02 15:04:05")) + sb.WriteString(" ") + //sb.WriteString(" ") + //sb.WriteString(f.prefix) + sb.WriteString(entry.Message) + sb.WriteString("\n") + + return sb.Bytes(), nil +} diff --git a/code/main.go b/code/main.go index bf7c98ab..3ad9f4d4 100644 --- a/code/main.go +++ b/code/main.go @@ -2,11 +2,9 @@ package main import ( "context" - "log" - "start-feishubot/handlers" "start-feishubot/initialization" - "start-feishubot/services/openai" + "start-feishubot/logger" "github.com/gin-gonic/gin" sdkginext "github.com/larksuite/oapi-sdk-gin" @@ -14,6 +12,7 @@ import ( "github.com/larksuite/oapi-sdk-go/v3/event/dispatcher" larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1" "github.com/spf13/pflag" + "start-feishubot/services/openai" ) var ( @@ -32,6 +31,7 @@ func main() { config.FeishuAppVerificationToken, config.FeishuAppEncryptKey). OnP2MessageReceiveV1(handlers.Handler). OnP2MessageReadV1(func(ctx context.Context, event *larkim.P2MessageReadV1) error { + logger.Debugf("收到请求 %v", event.RequestURI) return handlers.ReadHandler(ctx, event) }) @@ -52,6 +52,6 @@ func main() { cardHandler)) if err := initialization.StartServer(*config, r); err != nil { - log.Fatalf("failed to start server: %v", err) + logger.Fatalf("failed to start server: %v", err) } } diff --git a/code/services/openai/common.go b/code/services/openai/common.go index 7ac432c6..8ced9306 100644 --- a/code/services/openai/common.go +++ b/code/services/openai/common.go @@ -9,11 +9,11 @@ import ( "mime/multipart" "net/http" "net/url" - "strings" - "time" - "start-feishubot/initialization" + "start-feishubot/logger" "start-feishubot/services/loadbalancer" + "strings" + "time" ) type PlatForm string @@ -124,6 +124,9 @@ func (gpt *ChatGPT) doAPIRequestWithRetry(url, method string, //fmt.Println("--------------------") //fmt.Println("req", req.Header) //fmt.Printf("response: %v", response) + logger.Debug("req", req.Header) + + logger.Debugf("response %v", response) // read body if err != nil || response.StatusCode < 200 || response.StatusCode >= 300 { diff --git a/code/services/openai/gpt3.go b/code/services/openai/gpt3.go index 810daf81..341c81c7 100644 --- a/code/services/openai/gpt3.go +++ b/code/services/openai/gpt3.go @@ -2,6 +2,7 @@ package openai import ( "errors" + "start-feishubot/logger" "strings" "github.com/pandodao/tokenizer-go" @@ -86,6 +87,8 @@ func (gpt *ChatGPT) Completions(msg []Messages, aiMode AIMode) (resp Messages, gptResponseBody := &ChatGPTResponseBody{} url := gpt.FullUrl("chat/completions") //fmt.Println(url) + logger.Debug(url) + logger.Debug("request body ", requestBody) if url == "" { return resp, errors.New("无法获取openai请求地址") } @@ -93,6 +96,7 @@ func (gpt *ChatGPT) Completions(msg []Messages, aiMode AIMode) (resp Messages, if err == nil && len(gptResponseBody.Choices) > 0 { resp = gptResponseBody.Choices[0].Message } else { + logger.Errorf("ERROR %v", err) resp = Messages{} err = errors.New("openai 请求失败") } From c8f09a4dc7f67c0d9fc43c24eaf73dec0b23802e Mon Sep 17 00:00:00 2001 From: toeasy Date: Mon, 17 Apr 2023 21:17:11 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=BC=95=E5=85=A5=E6=97=A5=E5=BF=97logrus?= =?UTF-8?q?=EF=BC=8C=E5=B9=B6=E5=BC=80=E5=90=AF=E4=BA=86larksuite=E7=9A=84?= =?UTF-8?q?debug=20closed=20#198?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- code/go.mod | 1 + code/go.sum | 3 + code/handlers/card_clear_action.go | 8 +- code/handlers/card_common_action.go | 2 + code/handlers/card_pic_action.go | 10 ++- code/handlers/event_common_action.go | 1 + code/handlers/event_pic_action.go | 3 +- code/handlers/handler.go | 5 +- code/handlers/init.go | 5 +- code/handlers/msg.go | 8 +- code/initialization/gin.go | 3 +- code/initialization/lark_client.go | 6 +- code/logger/logger.go | 115 +++++++++++++++++++++++++++ code/main.go | 8 +- code/services/openai/common.go | 9 ++- code/services/openai/gpt3.go | 4 + 16 files changed, 170 insertions(+), 21 deletions(-) create mode 100644 code/logger/logger.go diff --git a/code/go.mod b/code/go.mod index 0ddc315d..8eae9efe 100644 --- a/code/go.mod +++ b/code/go.mod @@ -12,6 +12,7 @@ require ( github.com/pandodao/tokenizer-go v0.2.0 github.com/patrickmn/go-cache v2.1.0+incompatible github.com/pion/opus v0.0.0-20230123082803-1052c3e89e58 + github.com/sirupsen/logrus v1.9.0 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.14.0 gopkg.in/yaml.v2 v2.4.0 diff --git a/code/go.sum b/code/go.sum index 7f870c9b..301f587d 100644 --- a/code/go.sum +++ b/code/go.sum @@ -217,6 +217,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= @@ -396,6 +398,7 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/code/handlers/card_clear_action.go b/code/handlers/card_clear_action.go index 51bd582b..c1c1ab26 100644 --- a/code/handlers/card_clear_action.go +++ b/code/handlers/card_clear_action.go @@ -2,10 +2,9 @@ package handlers import ( "context" - - "start-feishubot/services" - larkcard "github.com/larksuite/oapi-sdk-go/v3/card" + "start-feishubot/logger" + "start-feishubot/services" ) func NewClearCardHandler(cardMsg CardMsg, m MessageHandler) CardHandlerFunc { @@ -23,6 +22,7 @@ func NewClearCardHandler(cardMsg CardMsg, m MessageHandler) CardHandlerFunc { func CommonProcessClearCache(cardMsg CardMsg, session services.SessionServiceCacheInterface) ( interface{}, error, bool) { + logger.Debugf("card msg value %v", cardMsg.Value) if cardMsg.Value == "1" { session.Clear(cardMsg.SessionId) newCard, _ := newSendCard( @@ -30,7 +30,7 @@ func CommonProcessClearCache(cardMsg CardMsg, session services.SessionServiceCac withMainMd("已删除此话题的上下文信息"), withNote("我们可以开始一个全新的话题,继续找我聊天吧"), ) - //fmt.Printf("session: %v", newCard) + logger.Debugf("session %v", newCard) return newCard, nil, true } if cardMsg.Value == "0" { diff --git a/code/handlers/card_common_action.go b/code/handlers/card_common_action.go index 7d89eefd..29ef6a8e 100644 --- a/code/handlers/card_common_action.go +++ b/code/handlers/card_common_action.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "start-feishubot/logger" larkcard "github.com/larksuite/oapi-sdk-go/v3/card" ) @@ -34,6 +35,7 @@ func NewCardHandler(m MessageHandler) CardHandlerFunc { return nil, err } //pp.Println(cardMsg) + logger.Debug("cardMsg ", cardMsg) for _, handler := range handlers { h := handler(cardMsg, m) i, err := h(ctx, cardAction) diff --git a/code/handlers/card_pic_action.go b/code/handlers/card_pic_action.go index 9e4a33b9..2c2d1902 100644 --- a/code/handlers/card_pic_action.go +++ b/code/handlers/card_pic_action.go @@ -2,6 +2,9 @@ package handlers import ( "context" + "fmt" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" + "start-feishubot/logger" "start-feishubot/services" @@ -47,7 +50,7 @@ func CommonProcessPicResolution(msg CardMsg, cardAction *larkcard.CardAction, cache services.SessionServiceCacheInterface) { option := cardAction.Action.Option - //fmt.Println(larkcore.Prettify(msg)) + fmt.Println(larkcore.Prettify(msg)) cache.SetPicResolution(msg.SessionId, services.Resolution(option)) //send text replyMsg(context.Background(), "已更新图片分辨率为"+option, @@ -56,8 +59,9 @@ func CommonProcessPicResolution(msg CardMsg, func (m MessageHandler) CommonProcessPicMore(msg CardMsg) { resolution := m.sessionCache.GetPicResolution(msg.SessionId) - //fmt.Println("resolution: ", resolution) - //fmt.Println("msg: ", msg) + + logger.Debugf("resolution: %v", resolution) + logger.Debug("msg: %v", msg) question := msg.Value.(string) bs64, _ := m.gpt.GenerateOneImage(question, resolution) replayImageCardByBase64(context.Background(), bs64, &msg.MsgId, diff --git a/code/handlers/event_common_action.go b/code/handlers/event_common_action.go index 4f79e163..d6827b52 100644 --- a/code/handlers/event_common_action.go +++ b/code/handlers/event_common_action.go @@ -69,6 +69,7 @@ func (*EmptyAction) Execute(a *ActionInfo) bool { sendMsg(*a.ctx, "🤖️:你想知道什么呢~", a.info.chatId) fmt.Println("msgId", *a.info.msgId, "message.text is empty") + return false } return true diff --git a/code/handlers/event_pic_action.go b/code/handlers/event_pic_action.go index 0fb69395..c3dedfdd 100644 --- a/code/handlers/event_pic_action.go +++ b/code/handlers/event_pic_action.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "start-feishubot/logger" "start-feishubot/initialization" "start-feishubot/services" @@ -36,7 +37,7 @@ func (*PicAction) Execute(a *ActionInfo) bool { mode := a.handler.sessionCache.GetMode(*a.info.sessionId) //fmt.Println("mode: ", mode) - + logger.Debug("MODE:", mode) // 收到一张图片,且不在图片创作模式下, 提醒是否切换到图片创作模式 if a.info.msgType == "image" && mode != services.ModePicCreate { sendPicModeCheckCard(*a.ctx, a.info.sessionId, a.info.msgId) diff --git a/code/handlers/handler.go b/code/handlers/handler.go index c3286f26..cfdc8070 100644 --- a/code/handlers/handler.go +++ b/code/handlers/handler.go @@ -3,6 +3,8 @@ package handlers import ( "context" "fmt" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" + "start-feishubot/logger" "strings" "start-feishubot/initialization" @@ -49,11 +51,12 @@ func judgeMsgType(event *larkim.P2MessageReceiveV1) (string, error) { func (m MessageHandler) msgReceivedHandler(ctx context.Context, event *larkim.P2MessageReceiveV1) error { handlerType := judgeChatType(event) + logger.Debug("handlerType", handlerType) if handlerType == "otherChat" { fmt.Println("unknown chat type") return nil } - //fmt.Println(larkcore.Prettify(event.Event.Message)) + logger.Debug("收到消息:", larkcore.Prettify(event.Event.Message)) msgType, err := judgeMsgType(event) if err != nil { diff --git a/code/handlers/init.go b/code/handlers/init.go index 5589359c..25ab953a 100644 --- a/code/handlers/init.go +++ b/code/handlers/init.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "start-feishubot/logger" "start-feishubot/initialization" "start-feishubot/services/openai" @@ -34,8 +35,10 @@ func Handler(ctx context.Context, event *larkim.P2MessageReceiveV1) error { } func ReadHandler(ctx context.Context, event *larkim.P2MessageReadV1) error { - _ = event.Event.Reader.ReaderId.OpenId + readerId := event.Event.Reader.ReaderId.OpenId //fmt.Printf("msg is read by : %v \n", *readerId) + logger.Debugf("msg is read by : %v \n", *readerId) + return nil } diff --git a/code/handlers/msg.go b/code/handlers/msg.go index 18ab272e..21610530 100644 --- a/code/handlers/msg.go +++ b/code/handlers/msg.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "errors" "fmt" + "start-feishubot/logger" "start-feishubot/initialization" "start-feishubot/services" @@ -70,7 +71,7 @@ func replyCard(ctx context.Context, // 服务端错误处理 if !resp.Success() { - fmt.Println(resp.Code, resp.Msg, resp.RequestId()) + logger.Errorf("服务端错误 resp code[%v], msg [%v] requestId [%v] ", resp.Code, resp.Msg, resp.RequestId()) return errors.New(resp.Msg) } return nil @@ -758,7 +759,10 @@ func SendRoleTagsCard(ctx context.Context, withHeader("🛖 请选择角色类别", larkcard.TemplateIndigo), withRoleTagsBtn(sessionId, roleTags...), withNote("提醒:选择角色所属分类,以便我们为您推荐更多相关角色。")) - replyCard(ctx, msgId, newCard) + err := replyCard(ctx, msgId, newCard) + if err != nil { + logger.Errorf("选择角色出错 %v", err) + } } func SendRoleListCard(ctx context.Context, diff --git a/code/initialization/gin.go b/code/initialization/gin.go index cdc93234..59e19749 100644 --- a/code/initialization/gin.go +++ b/code/initialization/gin.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "net/http" + //"start-feishubot/logger" "time" "github.com/gin-gonic/gin" @@ -35,7 +36,7 @@ func loadCertificate(config Config) (cert tls.Certificate, err error) { } func startHTTPServer(config Config, r *gin.Engine) (err error) { - log.Printf("http server started: http://localhost:%d/webhook/event\n", config.HttpPort) + log.Printf("http server started: http://localhost:%d/webhook/event\n\n", config.HttpPort) err = r.Run(fmt.Sprintf(":%d", config.HttpPort)) if err != nil { return fmt.Errorf("failed to start http server: %v", err) diff --git a/code/initialization/lark_client.go b/code/initialization/lark_client.go index 27ad97d5..5a0b27b1 100644 --- a/code/initialization/lark_client.go +++ b/code/initialization/lark_client.go @@ -2,12 +2,16 @@ package initialization import ( lark "github.com/larksuite/oapi-sdk-go/v3" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" ) var larkClient *lark.Client func LoadLarkClient(config Config) { - larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret) + + option := lark.WithLogLevel(larkcore.LogLevelDebug) + larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret, option) + } func GetLarkClient() *lark.Client { diff --git a/code/logger/logger.go b/code/logger/logger.go new file mode 100644 index 00000000..d42d7117 --- /dev/null +++ b/code/logger/logger.go @@ -0,0 +1,115 @@ +package logger + +import ( + "bytes" + "github.com/gin-gonic/gin" + "github.com/sirupsen/logrus" + "strings" +) + +var logger = logrus.New() + +func init() { + + logger.SetFormatter(&formatter{}) + + logger.SetReportCaller(true) + + gin.DefaultWriter = logger.Out + + logger.Level = logrus.DebugLevel + +} + +type Fields logrus.Fields + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + if logger.Level >= logrus.DebugLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Debugf(format, args...) + } +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + if logger.Level >= logrus.WarnLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Warnf(format, args...) + } +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + if logger.Level >= logrus.ErrorLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Errorf(format, args...) + } +} + +// Fatalf logs a message at level Fatal on the standard logger. +func Fatalf(format string, args ...interface{}) { + if logger.Level >= logrus.FatalLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Fatalf(format, args...) + } +} + +func Debug(format string, args ...interface{}) { + if logger.Level >= logrus.DebugLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Debug(format, args) + } +} + +// Info logs a message at level Info on the standard logger. +func Info(format string, args ...interface{}) { + if logger.Level >= logrus.InfoLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Info(format, args) + } +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(format string, args ...interface{}) { + if logger.Level >= logrus.WarnLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Warn(format, args) + } +} + +// Error logs a message at level Error on the standard logger. +func Error(format string, args ...interface{}) { + if logger.Level >= logrus.ErrorLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Error(format, args) + } +} + +// Fatal logs a message at level Fatal on the standard logger. +func Fatal(format string, args ...interface{}) { + if logger.Level >= logrus.FatalLevel { + entry := logger.WithFields(logrus.Fields{}) + entry.Fatal(format, args) + } +} + +// Formatter implements logrus.Formatter interface. +type formatter struct { + prefix string +} + +// Format building log message. +func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) { + var sb bytes.Buffer + + sb.WriteString("[" + strings.ToUpper(entry.Level.String()) + "]") + sb.WriteString(entry.Time.Format("2006-01-02 15:04:05")) + sb.WriteString(" ") + //sb.WriteString(" ") + //sb.WriteString(f.prefix) + sb.WriteString(entry.Message) + sb.WriteString("\n") + + return sb.Bytes(), nil +} diff --git a/code/main.go b/code/main.go index bf7c98ab..3ad9f4d4 100644 --- a/code/main.go +++ b/code/main.go @@ -2,11 +2,9 @@ package main import ( "context" - "log" - "start-feishubot/handlers" "start-feishubot/initialization" - "start-feishubot/services/openai" + "start-feishubot/logger" "github.com/gin-gonic/gin" sdkginext "github.com/larksuite/oapi-sdk-gin" @@ -14,6 +12,7 @@ import ( "github.com/larksuite/oapi-sdk-go/v3/event/dispatcher" larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1" "github.com/spf13/pflag" + "start-feishubot/services/openai" ) var ( @@ -32,6 +31,7 @@ func main() { config.FeishuAppVerificationToken, config.FeishuAppEncryptKey). OnP2MessageReceiveV1(handlers.Handler). OnP2MessageReadV1(func(ctx context.Context, event *larkim.P2MessageReadV1) error { + logger.Debugf("收到请求 %v", event.RequestURI) return handlers.ReadHandler(ctx, event) }) @@ -52,6 +52,6 @@ func main() { cardHandler)) if err := initialization.StartServer(*config, r); err != nil { - log.Fatalf("failed to start server: %v", err) + logger.Fatalf("failed to start server: %v", err) } } diff --git a/code/services/openai/common.go b/code/services/openai/common.go index 7ac432c6..8ced9306 100644 --- a/code/services/openai/common.go +++ b/code/services/openai/common.go @@ -9,11 +9,11 @@ import ( "mime/multipart" "net/http" "net/url" - "strings" - "time" - "start-feishubot/initialization" + "start-feishubot/logger" "start-feishubot/services/loadbalancer" + "strings" + "time" ) type PlatForm string @@ -124,6 +124,9 @@ func (gpt *ChatGPT) doAPIRequestWithRetry(url, method string, //fmt.Println("--------------------") //fmt.Println("req", req.Header) //fmt.Printf("response: %v", response) + logger.Debug("req", req.Header) + + logger.Debugf("response %v", response) // read body if err != nil || response.StatusCode < 200 || response.StatusCode >= 300 { diff --git a/code/services/openai/gpt3.go b/code/services/openai/gpt3.go index 810daf81..341c81c7 100644 --- a/code/services/openai/gpt3.go +++ b/code/services/openai/gpt3.go @@ -2,6 +2,7 @@ package openai import ( "errors" + "start-feishubot/logger" "strings" "github.com/pandodao/tokenizer-go" @@ -86,6 +87,8 @@ func (gpt *ChatGPT) Completions(msg []Messages, aiMode AIMode) (resp Messages, gptResponseBody := &ChatGPTResponseBody{} url := gpt.FullUrl("chat/completions") //fmt.Println(url) + logger.Debug(url) + logger.Debug("request body ", requestBody) if url == "" { return resp, errors.New("无法获取openai请求地址") } @@ -93,6 +96,7 @@ func (gpt *ChatGPT) Completions(msg []Messages, aiMode AIMode) (resp Messages, if err == nil && len(gptResponseBody.Choices) > 0 { resp = gptResponseBody.Choices[0].Message } else { + logger.Errorf("ERROR %v", err) resp = Messages{} err = errors.New("openai 请求失败") }